Scanning nextLine in Java
Just one question: why would I enter twice answer = in.nextLine();
? If this line is single, the program does not work as expected. Without the second line, the program doesn't ask you to enter a line.
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String answer = "Yes";
while (answer.equals("Yes")) {
System.out.println("Enter name and rating:");
String name = in.nextLine();
int rating = 0;
if (in.hasNextInt()) {
rating = in.nextInt();
} else {
System.out.println("Error. Exit.");
return;
}
System.out.println("Name: " + name);
System.out.println("Rating: " + rating);
ECTS ects = new ECTS();
rating = ects.checkRating(rating);
System.out.println("Enter \"Yes\" to continue: ");
answer = in.nextLine();
answer = in.nextLine();
}
System.out.println("Bye!");
in.close();
}
}
source to share
Scanner-Object has an internal cache.
- You run scann for
nextInt()
. - You press the key 1
- You press the key 2
- You push return
Now the internal cache has 3 characters and the scanner sees that the third character ( return) is not a number, so it nextInt()
only returns an integer between the 1st and 2nd characters ( 1, 2= 12).
-
nextInt()
returns 12.
Unfortunately, returnit is still part of the scanner cache.
-
You call
nextLine()
, but the Method looks in its cache for thenewline
token that was stored in the cache before the call was returnednextInt()
. -
nextLine()
returns a string of length 0. - The next one
nextLine()
has an empty cache! It will wait until the cache is filled with the nextnewline
token.
reset ()
There is a more elegant way to clear the cache instead of using nextLine()
:
in.reset();
source to share