Home >Java >javaTutorial >How to Prevent Infinite Loops When Handling Invalid Integer Input with Java's Scanner?

How to Prevent Infinite Loops When Handling Invalid Integer Input with Java's Scanner?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-11 17:08:18348browse

How to Prevent Infinite Loops When Handling Invalid Integer Input with Java's Scanner?

try/catch with InputMismatchException Looping Issue

When attempting to handle user input with a try/catch block and an InputMismatchException, you may encounter an infinite loop if the input is not an integer. To resolve this, ensure you call next() to advance the Scanner past the invalid input.

catch (Exception e) {
    System.out.println("Error!");
    input.next(); // Advance past invalid input
}

Additionally, it's advisable to use hasNextInt() to check for valid integer input before reading it.

while (bError) {
    if (scanner.hasNextInt())
        n1 = scanner.nextInt();
    else {
        scanner.next(); // Advance past invalid input
        continue;
    }
    // Repeat for n2
}

This approach ensures that the Scanner skips non-integer input and only proceeds with valid values, eliminating the need for exception handling.

The above is the detailed content of How to Prevent Infinite Loops When Handling Invalid Integer Input with Java's Scanner?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn