java - Using scanner.nextLine() -
this question has answer here:
i have been having trouble while attempting use nextline() method java.util.scanner.
here tried:
import java.util.scanner; class testrevised { public void menu() { scanner scanner = new scanner(system.in); system.out.print("enter sentence:\t"); string sentence = scanner.nextline(); system.out.print("enter index:\t"); int index = scanner.nextint(); system.out.println("\nyour sentence:\t" + sentence); system.out.println("your index:\t" + index); } }
example #1: example works intended. line string sentence = scanner.nextline();
waits input entered before continuing on system.out.print("enter index:\t");
.
this produces output:
enter sentence: hello. enter index: 0 sentence: hello. index: 0
// example #2 import java.util.scanner; class test { public void menu() { scanner scanner = new scanner(system.in); while (true) { system.out.println("\nmenu options\n"); system.out.println("(1) - this"); system.out.println("(2) - quit"); system.out.print("please enter selection:\t"); int selection = scanner.nextint(); if (selection == 1) { system.out.print("enter sentence:\t"); string sentence = scanner.nextline(); system.out.print("enter index:\t"); int index = scanner.nextint(); system.out.println("\nyour sentence:\t" + sentence); system.out.println("your index:\t" + index); } else if (selection == 2) { break; } } } }
example #2: example not work intended. example uses while loop , and if - else structure allow user choose do. once program gets string sentence = scanner.nextline();
, not wait input instead executes line system.out.print("enter index:\t");
.
this produces output:
menu options (1) - (2) - quit please enter selection: 1 enter sentence: enter index:
which makes impossible enter sentence.
why example #2 not work intended? difference between ex. 1 , 2 ex. 2 has while loop , if-else structure. don't understand why affects behavior of scanner.nextint().
i think problem that
int selection = scanner.nextint();
reads number, not end of line or after number. when you
string sentence = scanner.nextline();
this read remainder of line number on (with nothing after number suspect)
try placing scanner.nextline(); after each nextint() if intend ignore rest of line.
Comments
Post a Comment