java - How to store comma separated argument using scanner -
i taking user input using scanner , want store 2 argument given command line how ever able one. believe hasnextint() returns boolean value if there nextint, when enter non-int value doesnot break loop.
i have checked sources online , on stackoverflow before posting questions did not looking for.
scanner s = new scanner(system.in); int first = 0; int second = 0; system.out.println("please enter number: "); s.usedelimiter(","); while (s.hasnextint()) { first = s.nextint(); system.out.print("firstargument: " + first + "\n"); second = s.nextint(); system.out.print("secondargument: " + second + "\n"); }
the problem code calls s.hasnextint()
every odd-numbered input, tries take each even-numbered input without performing check. therefore, requires inputs this:
1,2,3,4,5,6,done 1,2,3,4,done 1,2,done
however, inputs result in exception:
1,2,3,4,5,done 1,2,3,done 1,done
note non-numeric input must appear after comma on same line.
to fix problem, add check before reading second value:
while (s.hasnextint()) { first = s.nextint(); if (!s.hasnextint()) break' second = s.nextint(); system.out.print("firstargument: " + first + "\n"); system.out.print("secondargument: " + second + "\n"); }
if allow other characters, such end-of-line markers, end comma-separated list, use different expression delimiters:
s.usedelimiter("[,\n]");
Comments
Post a Comment