问题
I'm new at programming and I am currently following a Java class where I must validate a user's scanner input. The code below seems to work but I think it's a little bit inefficient. There must be a better way to do this!
Your suggestions are welcome!
Here's what I've got:
do {
System.out.println("What is you age?");
while (!scSudoku.hasNextInt()) {
System.out.println("You must enter an number");
scSudoku.next();
}
age = scSudoku.nextInt();
if (age < 10 || age > 90) {
System.out.println("You age must be within 10 and 90");
}
} while (age < 10 || age > 90);
回答1:
Use nextLine()
to discard any bad input.
Prevent code-duplication by using a never-ending loop, and either break
or return
to exit the loop. I prefer isolating the code in a helper method and use return
.
private static int promptAge(Scanner sc) {
System.out.println("What is you age?");
for (;;) {
if (! sc.hasNextInt()) {
System.out.println("You must enter an number");
} else {
int age = sc.nextInt();
if (age >= 10 && age <= 90)
return age;
System.out.println("You age must be within 10 and 90");
}
sc.nextLine(); // discard (rest of) line of input
}
}
回答2:
Try replacing scSudoku.next();
with scSudoku.nextLine
. It might run a little smoother, but my Java is a little rusty.
I remember using nextLine
or nextln
instead of just next
, and the programs worked.
EDIT:
Try replacing scSudoku.next();
with scSudoku.nextln
. It appears that nextln
is more widely used.
EDIT 2:
Or just use nextWhateverYou'reUsing
.
来源:https://stackoverflow.com/questions/34907581/validate-input-of-a-scanner-is-it-an-integer-and-within-a-certain-number-range