I've encountered a rather odd problem with the Java Scanner getting user input. I made a practice program which first reads a double using nextDouble()
, outputs some trivial text and then uses the same scanner object to get a string input using nextLine()
.
Here is the code :
import java.util.Scanner;
public class UsrInput {
public static void main(String[] args) {
//example with user double input
Scanner reader = new Scanner(System.in);
System.out.println("Enter a number: ");
double input = reader.nextDouble();
if(input % 2 == 0){
System.out.println("The input was even");
}else if(input % 2 == 1){
System.out.println("The input was odd");
}else{
System.out.println("The input was not an integer");
}
//example with user string input
System.out.println("Verify by typing the word 'FooBar': ");
String input2 = reader.nextLine();
System.out.println("The string equal 'FooBar': " + input2.equals("FooBar"));
}
}
Now obviously my intention is to ask for a second input, and print if it's true or false that the string input2 equals 'FooBar'. However when I run this it skips the second input and immediately tells me it's not equal. However if I change reader.nextLine()
to reader.next()
it suddenly works.
It also works if I create a new Scanner instance and use reader2.nextLine()
So my question is why is my Scanner object not asking me for new input? If I print out the value of "input2" it's empty.