gpt4 book ai didi

java - Java 中的无限 do/while 循环。请指教

转载 作者:行者123 更新时间:2023-12-01 19:45:41 26 4
gpt4 key购买 nike

我是新来的,一般来说都是编码。我想要完成的是创建一个简单的猜谜游戏,提示用户输入一个数字,并将该数字与计算机生成的 1 到 100 之间的数字进行检查。我尝试这样做,以便玩家可以继续猜测,直到他们会得到正确的答案,并显示一个计数器,让玩家知道他们进行了多少次猜测尝试。问题是,给出正确答案后程序不会终止,而且我不知道我做错了什么。我将整个代码粘贴在底部以供引用,但我觉得问题出在“defineAnswer”方法中的以下语句中:

} else if (userAnswer == computerNumber) {
message = "Correct"
+ "\nNumber of Guesses: " + count;
success++;

我试图使用整数“成功”的值作为终止 do/while 循环的条件,但即使我尝试增加该值,循环仍会继续,就像该值正在被不断重置一样。如果是这样的话,我看不出我哪里出了问题。再说一遍,我对此还很陌生,但我会很感激任何意见。

import javax.swing.JOptionPane;

public class GuessingGame {

public static void main(String[] args) {
// generate a random number from 1 to 100
int computerNumber = (int) (Math.random() * 100 + 1);
// declare other variables
int success = 0;
int count = 0;
// display the correct guess for testing purposes
System.out.println("The correct guess would be " + computerNumber);
// prompt user for a guess
do {
count++;
String response = JOptionPane.showInputDialog(null,
"Enter a guess between 1 and 100");
int userAnswer = Integer.parseInt(response);
// display result
JOptionPane.showMessageDialog(null, determineGuess(userAnswer, computerNumber, success, count));
} while (success == 0);

}

public static String determineGuess(int userAnswer, int computerNumber,int success, int count) {
String message = null;
if (userAnswer <= 0 || userAnswer > 100) {
message = "Invalid guess"
+ "\nNumber of Guesses: " + count;
} else if (userAnswer == computerNumber) {
message = "Correct"
+ "\nNumber of Guesses: " + count;
success++;
} else if (userAnswer > computerNumber) {
message = "Incorrect, Too High"
+ "\nNumber of Guesses: " + count;
} else if (userAnswer < computerNumber) {
message = "Incorrect, Too Low"
+ "\nNumber of Guesses: " + count;
}
return message;
}
}

最佳答案

您没有更新 success 的值,每次循环运行时,它都会将 success 值设为 0,从而导致无限循环。

int success = 0;
int count = 0;
// display the correct guess for testing purposes
System.out.println("The correct guess would be " + computerNumber);
// prompt user for a guess
do {
count++;
String response = JOptionPane.showInputDialog(null,
"Enter a guess between 1 and 100");
int userAnswer = Integer.parseInt(response);
// display result
JOptionPane.showMessageDialog(null, determineGuess(userAnswer, computerNumber, success, count));
success=1;
} while (success == 0);

关于java - Java 中的无限 do/while 循环。请指教,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53477590/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com