Как выйти из программы, введя определенную букву внутри цикла Try-Catch While Loop? - PullRequest
0 голосов
/ 19 апреля 2019

В основном я хочу выйти из программы, когда пользователь вводит букву «q» вместо целого числа.

Пытался пару часов, пытался решить, добавив

if(quit.equalsIgnoreCase("q")){
System.exit(0)
}

В операторе try. Попытался удалить Scanner из оператора try и добавить его перед циклом while, а затем создать новую переменную, например, так:

String quit = "";
while (quit != "q"){
      //code
}

затем добавив способ выйти позже в коде снова, но это не сработало.

 while (true) {

                try {
                    int randomNumberOne = ThreadLocalRandom.current().nextInt(10, 21); //generates a number between 10 and 20
                    int randomNumberTwo = ThreadLocalRandom.current().nextInt(10, 21); //generates a number between 10 and 20
                    System.out.println("Type and enter \"q\" to quit at any time \n \n");

                    System.out.println(randomNumberOne + " % " + randomNumberTwo + " = ?"); //prints the question

                    Scanner userInput = new Scanner(System.in);
                    int remainderInput = userInput.nextInt();

                    if (remainderInput == randomNumberOne % randomNumberTwo) { //if they get the question right
                        userScore += 20; //adds 20 points
                        performance += 1; //adds 1 to the correct question counter
                        performancetotal += 1; //adds 1 to the total question counter
                        System.out.println("Correct answer, Current Score: " + userScore + ", performance: " + performance + "/" + performancetotal + "\n");
                        continue;
                    }

                    else { //if they get the question wrong
                        userScore += 0; //adds no points
                        performance += 0; //adds nothing to correct question counter
                        performancetotal += 1;
                        System.out.println("Incorrect answer, Current Score: " + userScore + ", performance: " + performance + "/" + performancetotal + "\n");
                        continue;
                    }

                 }

                catch (InputMismatchException e) {
                    System.out.println("Invalid input\n");

                }

         }
    }

Это мой текущий код, за исключением некоторой переменной вверху, которая не должна влиять на код.

Предполагается, что программа будет работать вечно до тех пор, пока пользователь не введет «q», после чего она остановится. Здесь есть операторы try / catch, так что они могут вводить только целые числа (кроме, конечно, «q»).

Любая помощь будет принята с благодарностью.

1 Ответ

1 голос
/ 19 апреля 2019

Вместо использования метода Scanner.nextInt() вы можете попробовать использовать nextLine(), чтобы получить строку. Затем вы можете проверить, равна ли эта строка "q". Если нет, вы можете разобрать строку в целое число с Integer.parseInt(yourString). Это может, однако, привести к NumberFormatException, если пользователь вводит что-либо, кроме числа или «q».

while (true) {

            try {
                int randomNumberOne = ThreadLocalRandom.current().nextInt(10, 21); //generates a number between 10 and 20
                int randomNumberTwo = ThreadLocalRandom.current().nextInt(10, 21); //generates a number between 10 and 20
                System.out.println("Type and enter \"q\" to quit at any time \n \n");

                System.out.println(randomNumberOne + " % " + randomNumberTwo + " = ?"); //prints the question

                Scanner userInput = new Scanner(System.in);
                String remainderInputStr = userInput.nextLine();
                if (remainderInputStr.equalsIgnoreCase("q")) {
                    System.exit(0);
                }
                int remainderInput = Integer.parseInt(remainderInputStr);
                if (remainderInput == randomNumberOne % randomNumberTwo) { //if they get the question right
                    userScore += 20; //adds 20 points
                    performance += 1; //adds 1 to the correct question counter
                    performancetotal += 1; //adds 1 to the total question counter
                    System.out.println("Correct answer, Current Score: " + userScore + ", performance: " + performance + "/" + performancetotal + "\n");
                    continue;
                } else { //if they get the question wrong
                    userScore += 0; //adds no points
                    performance += 0; //adds nothing to correct question counter
                    performancetotal += 1;
                    System.out.println("Incorrect answer, Current Score: " + userScore + ", performance: " + performance + "/" + performancetotal + "\n");
                    continue;
                }

            } catch (NumberFormatException e) {
                System.out.println("Invalid input\n");

            }
...