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

How to Avoid NoSuchElementException When Using Scanner.nextInt()?

DDD
Release: 2024-11-15 15:07:02
Original
413 people have browsed it

How to Avoid NoSuchElementException When Using Scanner.nextInt()?

Scanner Error with nextInt()

The Scanner class is a convenient tool for reading input from a console, but it can throw errors like NoSuchElementException if you try to read a type that doesn't exist in the input stream.

In the provided code:

Scanner s = new Scanner(System.in);
int choice = s.nextInt();
Copy after login

The nextInt() method attempts to read an integer from the standard input stream, but if no integer is available, it throws the NoSuchElementException. To avoid this error, always check if there is an integer to read using the hasNextInt() method:

Scanner s = new Scanner(System.in);
while(s.hasNextInt()) {
    int choice = s.nextInt();
    // Process the input
}
s.close();
Copy after login

This code will loop until there are no more integers to read, eliminating the risk of the NoSuchElementException. Additionally, use the hasNextInt() method to prevent entering an infinite loop if there are no integers to read.

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