我正在编写这个猜谜游戏,它允许用户输入一个数字作为最大数字。
然后,随机生成器将选择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);
}
}
答案 0 :(得分:1)
把它放在我的机器上,然后循环好了。它虽然破碎了;默认情况下,guess为0,并在异常后继续执行代码。如果发生随机数为0,程序将退出,因为它是正确的猜测。假设你的机器上发生了类似的事情?
您还没有将保护逻辑放在最初的“最大数量”位置。
答案 1 :(得分:0)
在try catch中使用continue;
。
代码就像
try {
guess = Integer.parseInt(sguess);
} catch (Exception nfe) {
JOptionPane.showMessageDialog(null, "That was not a number! ");
continue;
}
答案 2 :(得分:0)
虽然我无法看到您所描述的问题,但我建议您将比较代码放在try块中,这样您就可以确保在进行任何比较之前正确设置guess变量:< / p>
try {
guess = Integer.parseInt(sguess);
if (guess < answer) {
JOptionPane.showMessageDialog(null, "That is too LOW!");
lowcount++;
} else if (guess > answer) {
JOptionPane.showMessageDialog(null, "That is too HIGH!");
highcount++;
}
} catch (Exception nfe) {
JOptionPane.showMessageDialog(null, "That was not a number! ");
}