Java Scanner Input Validation
Consider the following method, which is designed to read and validate user input.
public static int getValidScore() {
Scanner scan = new Scanner(System.in);
System.out.print("Enter a score (0-100): ");
while (!scan.hasNextInt()) {
System.out.print("Invalid input. Enter an integer: ");
scan.next(); // Clear invalid input
}
int score = scan.nextInt();
while (score < 0 || score > 100) {
System.out.print("Score must be 0-100. Try again: ");
while (!scan.hasNextInt()) {
System.out.print("Invalid input. Enter an integer: ");
scan.next();
}
score = scan.nextInt();
}
return score;
}
What is the primary purpose of the scan.next() calls within the getValidScore method?
A
To convert String input into integer format for processing
B
To read the next valid integer from the input stream
C
To remove invalid non-integer input from the Scanner’s input buffer
D
To reset the Scanner object to accept new input
Question Leaderboard
Not enough data yet to show leaderboard.
APFIVE