Home > Java > javaTutorial > body text

How to Avoid the 'java.util.NoSuchElementException' When Using Scanner.nextInt()?

Susan Sarandon
Release: 2024-11-11 20:11:03
Original
1005 people have browsed it

How to Avoid the

Scanner Error with nextInt()

When using the Scanner class to read an integer (int) from the keyboard, you may encounter the error: java.util.NoSuchElementException. This error occurs when there is no integer available to read from the input stream.

To resolve this issue, use the hasNextInt() method to check if an integer is available before calling nextInt(). The hasNextInt() method returns true if an integer is available, and false if not. Here's how you can implement it:

Scanner s = new Scanner(System.in);

if (s.hasNextInt()) {
    int choice = s.nextInt(); // Read the integer without fear of NoSuchElementException
} else {
    System.out.println("No integer found in the input.");
}

s.close();
Copy after login

The above is the detailed content of How to Avoid the 'java.util.NoSuchElementException' When Using Scanner.nextInt()?. 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