Edited (3/18/2016 at 9:10 PM):
I am trying to write a program that loops until valid values are inputted by the user--month, day, and year. Note that year is a string so that, later in the program, I can print it out correctly if the year was something like "01".
while (true){
try{
System.out.println("Please enter a month in numeric form");
month = input.nextInt();
System.out.println("Please enter a day in numeric form");
day = input.nextInt();
System.out.println("Please enter a two-digit year");
if (input.hasNextInt() == true){
year = input.next();
}
else{
throw new java.util.InputMismatchException();
}
break;
}
catch(Exception e){
System.err.println(e);
System.out.println("\nOne of your inputs was not valid.");
System.out.println(input.nextLine()); // problem line
}
}
The last line of the catch block seems to be causing the odd behavior. I have decided to print that line to see what input.nextLine() contains; if I leave it as input.next(), the program works perfectly. Here is the output if I enter some bad input for the year in the above code:
Please enter a month in numeric form
8
Please enter a day in numeric form
2
Please enter a two-digit year
badinput
java.util.InputMismatchException
One of your inputs was not valid.
Please enter a month in numeric form
java.util.InputMismatchException
One of your inputs was not valid.
badinput
Please enter a month in numeric form
The output I should be getting (which is what happens if I I leave it as input.next()) is
Please enter a month in numeric form
8
Please enter a day in numeric form
2
Please enter a two-digit year
badinput
java.util.InputMismatchException
One of your inputs was not valid.
badinput
Please enter a month in numeric form
It is a minute difference but I thought I understood the behavior of nextLine() and next()--now it's clear my intuition is wrong. To my understanding, next() consumes the current token while nextLine() consumes the entire current line--shouldn't they accomplish the same thing here? Can someone explain?