如果用户输入字母而不是数字,如何在循环中添加错误语句,但程序应该继续
package sample;
import java.util.Scanner;
import java.util.Random;
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: ");
playerGuess = scan.nextInt();
numberOfAttempts++;
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.");
}
}
}
}
我的程序工作得很好,但我忘记了如何在循环中添加错误语句。有人可以帮助我在哪里以及如何添加一个错误声明,当用户输入字母而不是数字?提前感谢!:)))
您可以使用try和catch块检查错误。您所要做的就是将容易出错的代码包装在try块中,检查特定的异常并处理它。不要让接球空着,这是一种不好的做法。您可以这样做,但我建议使用if语句来检查输入是否包含数字