Are you taking CLEP classes? Try clep.ai
| preferred AP College board partner for AP classes
AP Computer Science A/Unit 2: Using Objects
Start Practice TestPractice Test
About Exam
medium Solved by 2 students

Java Scanner Input Validation

< Prev
Next >

Develop code to read input.

A programmer writes the following method 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() statements in this 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
Report Question
Mark for review

Question Leaderboard

Not enough data yet to show leaderboard.

No comments yet. Be the first to comment!

AI Tutor

How can I help?

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