0
Why does in.nextLine jumps into the next line without catching the input from board when it is in a loop?
i have a function that reads the name (string) and score (int) of n people... so i want the program to read this 2 things for each person (not only all the names first and after only all the scores) so y wrote the "in.nextLine" and "in.nextInt" for each person.... both in the same loop... but de last "in.next" just doesn't catches the input from board... instead it continues to the line that continues the loop...
3 Réponses
+ 6
When user gives an integer/double/float/char input and presses ENTER, the ENTER is considered as a newLine and this new line is accepted as next string input. So it doesn't wait for any other string input. As solution, what we can do is, add a scanner_name.nextLine() after the integer input is taken. This way the ENTER will be consumed.
See the following example:
Scanner input = new Scanner(System.in);
int a = input.nextInt();
input.nextLine(); // consumes ENTER
String s = input.nextLine();
+ 1
The method nextLine() consumes the new line character
+ 1
Like Shamima Yasmin make noted .nextLine and .nextXXX familty function works differently in handling newline... Read this thread
https://www.sololearn.com/discuss/1516044/?ref=app