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
Release: 2024-12-11 17:08:18
Original
295 people have browsed it

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
}
Copy after login

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
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template