您好,我正在制作一个游戏,并且正在尝试对其进行编程,因此用户正在考虑一个随机数,并且程序会尝试对其进行猜测。我必须使用消息对话框(这是一个学校项目),它询问用户该数字是否太高,太低或正确,但是当数字太低时,它将猜测更高的数字。有什么问题(假设计数已初始化为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;
}
答案 0 :(得分:0)
问题是您从不更新n。插入while循环,当您询问它是否太高或太低时,会将用户的答案存储在另一个变量中。您需要像开始时那样将用户答案存储在n中。
答案 1 :(得分:0)
进行一些更改可能会使此操作更容易理解。我认为,基本问题是循环中要检查“ n”,但是要在if
语句中重新收集结果。
您可以将计数增加从单个if
语句中移出,并允许在循环内收集响应。
int min = 0;
int max = 100;
// loop while an incorrect guess
while (! correctGuess) {
// do a binary search
// max and min are updated on each check
int progNum = ((max - min) / 2) + min;
// collect the response
String n = JOptionPane.showInputDialog("Is " + progNum + " too high, too low, or correct?", " ");
// cancel by user
if (n == null) {
break;
}
// user made a guess
++count;
if (n.equals("correct")) {
OptionPane.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
continue; // program stops
}
else if (n.equals("too high")) {
max = progNum - 1;
}
else if (n.equals("too low")) {
min = progNum + 1;
}
}
编辑:您可能希望仔细查看下一个猜测数字的生成方式。我认为纯二进制搜索方法比选择一个范围内的随机数更有效。
编辑2:您可以看到基本的二进制搜索方法at this link here。