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

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

DDD
Release: 2024-11-10 22:12:02
Original
219 people have browsed it

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

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();
Copy after login

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template