Как отобразить сообщение об ошибке вместо java исключение? - PullRequest
1 голос
/ 06 апреля 2020

Я пытаюсь создать игру-угадайку для задания 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!");


    }

}

1 Ответ

1 голос
/ 06 апреля 2020

попробуйте что-то вроде этого:

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

Это заменит

int guess = sc.nextInt();
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...