i using scanner methods nextint() , nextline() reading input. basically, looks this:
system.out.println("enter numerical value"); int option; option = input.nextint();//read numerical value input system.out.println("enter 1st string"); string string1 = input.nextline();//read 1st string (this skipped) system.out.println("enter 2nd string"); string string2 = input.nextline();//read 2nd string (this appears right after reading numerical value) the problem after entering numerical value, first input.nextline() skipped , second input.nextline() executed, output looks this:
enter numerical value 3 //this input enter 1st string //the program supposed stop here , wait input, skipped enter 2nd string //and line executed , waits input i tested application , looks problem lies in using input.nextint(). if delete it, both string1 = input.nextline() , string2 = input.nextline() executed want them be.
that's because scanner.nextint method not consume last newline character of input, , newline consumed in next call scanner.nextline.
workaround:
either fire blank
scanner.nextlinecall afterscanner.nextintconsume rest of line including newlineint option = input.nextint(); input.nextline(); // consume newline left-over string str1 = input.nextline();or, better, if read input through
scanner.nextline, convert input integer usinginteger.parseint(string)method.int option = 0; try { option = integer.parseint(input.nextline()); } catch (numberformatexception e) { e.printstacktrace(); } string str1 = input.nextline();
you encounter similar behaviour when use scanner.nextline after scanner.next() or scanner.nextfoo method (except nextline itself).
Comments
Post a Comment