我正在编写这个猜谜游戏,它允许用户输入一个数字作为最大数字。
然后随机生成器将在 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);
}
}
最佳答案
在我的机器上运行它,它循环正常。虽然它坏了; guess默认为0,你继续执行异常后的代码。如果碰巧随机数为 0,程序将退出,因为它是正确的猜测。假设你的机器上发生了这样的事情?
您也没有在最初的“您的最大数量是多少”位周围放置保护逻辑。
关于java - 如何修复这个基本程序? Java do-while 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29056866/