| preferred AP College board partner for AP classes
AP Computer Science A/Unit 2: Using Objects
Start Practice TestPractice Test
Share
About Exam
medium Solved by 2 students
Java Scanner Input Validation
< Prev
Next >

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

Hint
Did You Know?
Explain Why
Explain All Answers
Check Answer
Show Correct Answer

Question Leaderboard

Not enough data yet to show leaderboard.

AI Tutor

How can I help?

APFIVE © 2020.
Email: apfive@apfive.org|Privacy Policy