捕获InputMissMatchException后继续while循环,Java

问题描述 投票:0回答:1

我是 Java 新手,在捕获异常后遇到问题。捕获异常后程序结束,但我想继续循环。该程序的用途是,用户通过扫描仪输入 1 到 10 之间的数字,直到输入的数字等于之前定义的随机数。

public class GuessingGame {

    public static void main(String[] args) {

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

        int min = 1;
        int max = 1000;

        int randomNumber = (int) (Math.random() * (max - min) + 1) + min;

        Scanner scanner = new Scanner(System.in);

        int firstDraw = 1;
        int maxDraw = 1000;

        try {

            while (firstDraw < maxDraw) {

                System.out.println("Please enter your guess: ");

                int guessingNumber = scanner.nextInt();

                if (guessingNumber < randomNumber) {
                    System.out.println("Too small!");
                } else if (guessingNumber > randomNumber) {
                    System.out.println("Too big!");
                } else {
                    System.out.println("You win");
                }
                firstDraw++;
            }
        } catch (InputMismatchException e){
            System.out.println("Not a number - try again!");
        }
    }
}

我想问题是,我要在哪里放置 try-catch 块。我尝试了几种可能性,但没有得到正确的解决方案。如果我只是输入数字,程序就会运行并结束,直到我猜到正确的数字为止。但如果我使用字母而不是数字,它就会结束程序。我也看到过一些类似的问题,但我真的不明白

感谢你们的帮助:)

java while-loop try-catch
1个回答
0
投票

这可能就是你想要的?

public static void main(String[] args) {

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

    int min = 1;
    int max = 1000;

    int randomNumber = (int) (Math.random() * (max - min) + 1) + min;

    int firstDraw = 1;
    int maxDraw = 1000;


        while (firstDraw < maxDraw) {

            System.out.println("Please enter your guess: ");

            try {
                Scanner scanner = new Scanner(System.in);
                int guessingNumber = scanner.nextInt();

                if (guessingNumber < randomNumber) {
                    System.out.println("Too small!");
                } else if (guessingNumber > randomNumber) {
                    System.out.println("Too big!");
                } else {
                    System.out.println("You win");
                    break;
                }
                firstDraw++;

            } catch (InputMismatchException e){
                System.out.println("Not a number - try again!");
            }

        }

}
© www.soinside.com 2019 - 2024. All rights reserved.