如何在Java循环中添加错误提示:用户输入字母而非数字时程序继续执行
Great question! The problem you're hitting is that Scanner.nextInt() throws an InputMismatchException when the user enters anything that isn't an integer, which crashes your program immediately. Let's fix that with simple, robust error handling that keeps the game running and gives clear feedback to the user.
Solution 1: Use hasNextInt() for Defensive Input Checking
This is the cleaner, more proactive approach—we check if the input is valid before trying to read it. Here's your modified code:
package sample; import java.util.Scanner; import java.util.Random; import java.util.InputMismatchException; public class Main { public static void main(String[] args) { Scanner scan = new Scanner(System.in); Random rand = new Random(); int playerGuess; int randomNum = rand.nextInt(50) + 1; int numberOfAttempts = 0; while (true) { System.out.println("Guess a number from 1 to 50: "); // First, check if the input is a valid integer if (scan.hasNextInt()) { playerGuess = scan.nextInt(); numberOfAttempts++; // Your original game logic stays the same if (playerGuess == randomNum) { System.out.println("Congratulations! The number was: " + randomNum); System.out.println("You got it in " + numberOfAttempts + " attempts."); break; } else if (randomNum > playerGuess) { System.out.println("Your guess is too low. Try again."); } else { System.out.println("Your guess is too high. Try again."); } } else { // Handle non-numeric input System.out.println("Oops! That's not a valid number. Please enter an integer between 1 and 50."); scan.next(); // Critical: Clear the invalid input from the scanner buffer } } scan.close(); // Don't forget to clean up the scanner! } }
Key Details to Note:
scan.hasNextInt(): This method checks if the next token in the input stream is an integer. It returnstrueif it is, so we only proceed to read the input when we know it's valid.scan.next()in the else block: If the input is invalid, we need to consume that invalid token (like a letter or symbol) from the scanner's buffer. Without this, the scanner will keep re-reading the same invalid input forever, causing an infinite loop.
Solution 2: Use Try-Catch to Handle Exceptions
If you prefer a reactive approach (catching the exception when it happens), here's how that would look:
package sample; import java.util.Scanner; import java.util.Random; import java.util.InputMismatchException; public class Main { public static void main(String[] args) { Scanner scan = new Scanner(System.in); Random rand = new Random(); int playerGuess; int randomNum = rand.nextInt(50) + 1; int numberOfAttempts = 0; while (true) { System.out.println("Guess a number from 1 to 50: "); try { // Attempt to read the integer—this will throw an exception if input is invalid playerGuess = scan.nextInt(); numberOfAttempts++; // Original game logic if (playerGuess == randomNum) { System.out.println("Congratulations! The number was: " + randomNum); System.out.println("You got it in " + numberOfAttempts + " attempts."); break; } else if (randomNum > playerGuess) { System.out.println("Your guess is too low. Try again."); } else { System.out.println("Your guess is too high. Try again."); } } catch (InputMismatchException e) { // Catch the exception and notify the user System.out.println("Error: Invalid input! Please enter a whole number."); scan.next(); // Again, clear the invalid input to avoid infinite loops } } scan.close(); } }
Both approaches work, but the first one (hasNextInt()) is generally preferred because it avoids throwing exceptions unnecessarily and makes the code flow more intuitive.
内容的提问来源于stack exchange,提问作者John Cedrick De Leon

