Home  >  Article  >  Java  >  How to Prevent 'java.util.NoSuchElementException' When Using Scanner.nextInt()?

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

DDD
DDDOriginal
2024-11-10 22:12:02201browse

How to Prevent

Error Handling for nextInt() in Scanner

When attempting to retrieve an integer using Scanner.nextInt(), users occasionally encounter the error:

java.util.NoSuchElementException
    at java.util.Scanner.throwFor(Scanner.java:907)
    at java.util.Scanner.next(Scanner.java:1530)
    at java.util.Scanner.nextInt(Scanner.java:2160)
    at java.util.Scanner.nextInt(Scanner.java:2119)

This error arises when the input stream contains no integer for nextInt() to read. One method for resolving this is to employ hasNexInt(). This function verifies the presence of an integer before attempting to read it.

Scanner s = new Scanner(System.in);
int choice = 0;

if(s.hasNextInt()) 
{
   choice = s.nextInt();
}

s.close();

This modification ensures that nextInt() is only called when there is an integer available to read, preventing the error. Additionally, it is good practice to close the scanner when finished to release system resources.

The above is the detailed content of How to Prevent '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