В основном я хочу выйти из программы, когда пользователь вводит букву «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»).
Любая помощь будет принята с благодарностью.