【问题标题】:How can I add an error statement in a loop if the user entered letters instead of numbers如果用户输入字母而不是数字,如何在循环中添加错误语句
【发布时间】:2021-12-14 18:15:44
【问题描述】:

如果用户输入字母而不是数字但程序应该继续,我如何在循环中添加错误语句

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.");
            }
        }
    }
}

我的程序运行良好,但我忘记了如何在循环中添加错误语句。当用户输入字母而不是数字时,有人可以帮我在哪里以及如何添加错误语句吗?先感谢您! :)))

【问题讨论】:

  • 声明playerguess并初始化为= 0。使用变量作为while循环的条件'(playerGuess == 0)`。将playerGuess = scan.nextInt(); 代码行放在try/catch 块中。将所有其他代码放在try 代码块中,最后添加playerGuess = 0;。在catch 块中,将错误通知用户并使playerGuess 变量= 0。同时使用ENTER 键击中的换行符('scan.nextLine();')。如果你不记得如何......你现在应该。

标签: java loops random error-handling


【解决方案1】:

您可以使用 try 和 catch 块检查错误。您所要做的就是将容易出错的代码包装在 try 块中并检查特定异常并处理它。不要只是让捕获物空着,这是一种不好的做法。 你可以这样做,但我建议使用 if 语句来检查你的输入是否包含数字

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多