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

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

DDD
DDDOriginal
2024-11-13 12:04:02931browse

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

Scanner Int Input Error

When attempting to use the Scanner class to obtain an integer from user input, you may encounter the following error:

java.util.NoSuchElementException

This error occurs when the Scanner object tries to read an integer but finds no available value. To fix it, ensure that the input stream has an integer to read before calling nextInt().

The Scanner class provides the hasNextXXXX() methods for verifying the availability of specific data types. In this case, use hasNextInt() to check if an integer is ready to be read.

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

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

s.close();

By checking if an integer exists before attempting to read it, you can avoid the NoSuchElementException error.

The above is the detailed content of How to Avoid `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
Previous article:Ask the Expert - I/ONext article:Ask the Expert - I/O