Home >Java >javaTutorial >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!