Reputation: 53
First post/question here and very new to java. Trying to make a small text based movie database app. One part of it is to add a review. The problem is when I just hit [enter] when asked for a Score number [0-10] on the review, the prompt just drops one step down and keeps waiting for input. I want it to be impossible to leave this field blank. Here is what I have so far:
int score;
do {
while (!sc.hasNextInt()) {
sc.next();
System.out.print("\nInvalid input! ");
System.out.print("Please enter a number from 0-10: ");
}
score = sc.nextInt();
if (!(score >= 0 && score <= 10)) {
System.out.print("\nInvalid input! ");
System.out.print("Please enter a number from 0-10: ");
}
} while (!(score >= 0 && score <= 10 ));
Upvotes: 1
Views: 361
Reputation: 159165
Scanner
is reading tokens, i.e. text separated by whitespaces. That means, that as long as you just press Enter, the next token hasn't even started yet.
One of the fallacies of Scanner
is that it's so easy to use, but even easier to misuse, e.g. mishandling user input.
Example: What should happen if used enters 123 abc<enter>
? Your code will read 123
and continue, leaving abc
in the buffer for the next prompt, which might want text and hence read the abc
as that text. Oops!!
Most of the time, to handle bad user input, you should never use hasNextXxx()
and nextXxx()
methods other than nextLine()
. It's the only way to ensure you get one answer (input) for one prompt.
So, you should do something like this:
int score;
for (;;) {
System.out.print("Please enter a number from 0-10: ");
String line = sc.nextLine();
try {
score = Integer.parseInt(line.trim());
} catch (NumberFormatException e) {
System.out.println("Invalid input! Not a number.");
continue;
}
if (score < 0 || score > 10) {
System.out.println("Invalid input! Out of range.");
continue;
}
break;
}
Upvotes: 2