【问题标题】:How to display error message instead of java exception?如何显示错误消息而不是java异常?
【发布时间】:2020-04-06 19:50:59
【问题描述】:

我正在尝试为 Java 作业制作猜谜游戏,除了异常处理外,我拥有所需的一切,你看,我正试图让它显示错误消息,而不是在线程“main”java.util 中显示异常.InputMismatchException 当有人尝试以字母形式输入数字时。遵循我的代码。 (我知道我需要尝试一下,但我不知道该放什么。)

package guessNumber;


import java.util.Scanner;

public class GuessNumberApp {

    public static void main(String[] args) {
        final int LIMIT = 10;

        System.out.println("Guess the number!");
        System.out.println("I'm thinking of a number from 1 to " + LIMIT);
        System.out.println();

        // get a random number between 1 and the limit
        double d = Math.random() * LIMIT; // d is >= 0.0 and < limit
        int number = (int) d;             // convert double to int
        number++;                        // int is >= 1 and <= limit

        // prepare to read input from the user
        Scanner sc = new Scanner(System.in);
        int count = 1;



        while (true) {
            int guess = sc.nextInt();
            System.out.println("You guessed: " + guess);


            if (guess < 1 || guess > LIMIT) {
                System.out.println("Your Guess is Invalid.");
                continue;
            }

            if (guess < number) {
                System.out.println("Too Low.");
            } else if (guess > number) {
                System.out.println("Too High.");
            } else {
                System.out.println("You guessed it in " + count + " tries.\n");
                break;
            }

            count++;
        }


        System.out.println("Bye!");


    }

}

【问题讨论】:

  • 可以使用 java.util.Random 类生成随机数

标签: java eclipse exception


【解决方案1】:

试试这样的:

try {
    int guess = sc.nextInt();
} catch(InputMismatchException e) {
    System.out.println("some nice error message");
    continue;
}

这将取代

int guess = sc.nextInt();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-24
    • 1970-01-01
    • 1970-01-01
    • 2023-03-12
    • 2011-11-06
    • 2011-07-12
    相关资源
    最近更新 更多