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

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

Susan Sarandon
Susan SarandonOriginal
2024-11-11 20:11:031058browse

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();

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!

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