Я пишу эту игру угадывания, которая позволяет пользователю вводить число как максимальное число.Как исправить эту базовую программу? Java do-while loop
Затем случайный генератор выбирает число от 1 до максимального числа, введенного пользователем.
Он сохранит и отобразит количество высоких догадок и низких догадок.
Проблема, с которой я столкнулась, - это цикл программы и проверка.
Я не могу заставить программу зацикливаться после того, как пользователь ввел неправильный ввод, т. Е. Не целое число.
Я хочу, чтобы он вернулся к другому вопросу после отображения сообщения об ошибке.
Я использую try/catch, но после сообщения об ошибке программа не позволяет пользователю вводить другой номер для продолжения игры.
import java.util.ArrayList;
import java.util.Random;
import javax.swing.JOptionPane;
public class guessinggame { // class name
public static void main(String[] args) { // main method
String smax = JOptionPane.showInputDialog("Enter your maximum number for the Guessing Game:");
int max = Integer.parseInt(smax);
do {
if (max > 10000) {
JOptionPane.showMessageDialog(null, "Oh no! Please keep your number less than 10,000.");
smax = JOptionPane.showInputDialog("Enter your maximum number for the Guessing Game:");
max = Integer.parseInt(smax);
}
} while (max > 10000);
int answer, guess = 0, lowcount = 0, highcount = 0, game;
String sguess;
Random generator = new Random();
answer = generator.nextInt(max) + 1;
ArrayList<String> buttonChoices = new ArrayList<>(); // list of string arrays called buttonChoices
buttonChoices.add("1-" + max + " Guessing Game");
Object[] buttons = buttonChoices.toArray(); // turning the string arrays into objects called buttons
game = JOptionPane.showOptionDialog(null, "Play or Quit?", "Guessing Game",
JOptionPane.PLAIN_MESSAGE, JOptionPane.QUESTION_MESSAGE,
null, buttons, buttonChoices.get(0));
do {
sguess = JOptionPane.showInputDialog("I am thinking of a number between 1 and " + max + ". Have a guess:");
try {
guess = Integer.parseInt(sguess);
} catch (Exception nfe) {
JOptionPane.showMessageDialog(null, "That was not a number! ");
}
if (guess < answer) {
JOptionPane.showMessageDialog(null, "That is too LOW!");
lowcount++;
} else if (guess > answer) {
JOptionPane.showMessageDialog(null, "That is too HIGH!");
highcount++;
}
} while (guess != answer);
JOptionPane.showMessageDialog(null, "Well Done!" + "\n---------------" + "\nThe answer was " + answer + "\nLow Guesses: " + lowcount
+ "\nHigh Guesses: " + highcount + "\n\nOverall you guessed: " + (lowcount + highcount) + " Times");
System.exit(0);
}
}