Scanner Error with nextInt()
When using the Scanner class to read an integer (int) from the keyboard, you may encounter the error: java.util.NoSuchElementException. This error occurs when there is no integer available to read from the input stream.
To resolve this issue, use the hasNextInt() method to check if an integer is available before calling nextInt(). The hasNextInt() method returns true if an integer is available, and false if not. Here's how you can implement it:
Scanner s = new Scanner(System.in); if (s.hasNextInt()) { int choice = s.nextInt(); // Read the integer without fear of NoSuchElementException } else { System.out.println("No integer found in the input."); } s.close();
The above is the detailed content of How to Avoid the 'java.util.NoSuchElementException' When Using Scanner.nextInt()?. For more information, please follow other related articles on the PHP Chinese website!