java - 计算机猜谜游戏中的消息对话框
问题描述
你好我正在制作一个游戏,我正在尝试对其进行编程,以便用户正在考虑一个随机数并且程序试图猜测它。我必须使用消息对话框(这是一个学校项目),它会询问用户数字是否太高、太低或正确,但是当数字太低时,它会猜测更高的数字。问题是什么?(假设计数已初始化为 0。)
boolean correctGuess = false; // when computer guesses incorrectly, correctGuess is false
String n = JOptionPane.showInputDialog("Is " + progNum + " too high, too low, or correct?", " ");
while(correctGuess == false) // when the computer is guessing
{
if(n.equals("correct")) // if the number is correct
{
count++; // update number of guesses
JOptionPane.showMessageDialog(null, "Yay! " + progNum + " was correct! It took the computer " + count + " guesses."); // correct guess, displays number of guesses
correctGuess= true; // computer guessed the correct number
break; // program stops
}
else if(n.equals("too high")) // number is too high, prog generates lower number
{
count++; // update number of guesses
int max = (progNum - 1); // guess was too high so progNum-1 is the max
int min = 1; // min value is progNum + 1 since progNum is too high
progNum = generator.nextInt((max - min) + 1) + min; // new range for progNum between 1 and progNum1 - 1
String tooHigh = JOptionPane.showInputDialog("Is " + progNum + " too high, too low, or correct?", " "); // asks user
if (tooHigh == null)
return;
}
else if(n.equals("too low")) // number is too low, prog generates higher number
{
count++; // update number of guesses
int max = 100; // generate a range of values for another random guess
int min = (progNum + 1); // min value is progNum + 1 since progNum is too low
progNum = generator.nextInt((max - min) + 1) + min; // new range for progNum between 1 and progNum1 + 1
String tooLow = JOptionPane.showInputDialog("Is " + progNum + " too high, too low, or correct?", " "); // asks user
if (tooLow == null)
return;
}
解决方案
问题是你永远不会更新 n。在 while 循环中,当您询问它是否太高或太低时,您将用户的答案存储在另一个变量中。您需要将用户答案存储在 n 中,就像您在开始时所做的那样。