该程序是一个游戏,用户必须猜测神奇的数字才能获胜。我是java新手,还在学习中。当我输入 53 时,它只是再次询问问题,而不是显示输出。我确信这是一个简单的错误,我只是没有发现。谢谢!
import javax.swing.JOptionPane;
class NumberFrom1To100 {
public static void main(String[] args) {
boolean stillplaying = true;
double answer = 53;
double userAnswer;
String userInput;
while (stillplaying == true) {
userInput = JOptionPane.showInputDialog("Guess a number between 1 and 100.");
userAnswer = Double.parseDouble(userInput);
while (userAnswer != 53) {
if (userAnswer < 53) {
JOptionPane.showMessageDialog(null, "You picked a number LESS than the mystery number. Try again.");
break;
} else if (userAnswer > 53) {
JOptionPane.showMessageDialog(null, "You picked a number GREATER than the mystery number. Try again.");
break;
} else if (userAnswer == 53) {
JOptionPane.showMessageDialog(null, "Congratulations! You just won 5 brownie points!");
break;
}
}
}
/* System.exit(0); */
}
}
最佳答案
内部 while 循环不仅不需要,而且还会破坏您的程序。两种情况,userAnswer
为 53
或不是。让我们检查一下这两种情况。
不等于53
将触发while循环。如果它小于、等于(它永远不可能)或大于53
,它将中断。这使得循环变得过时。
等于53
根本不会触发循环,这就是您现在遇到的结果。
import javax.swing.JOptionPane;
class NumberFrom1To100
{
public static void main(String[] args) {
boolean stillplaying = true;
double answer = 53;
double userAnswer;
String userInput;
while (stillplaying) {
userInput = JOptionPane.showInputDialog("Guess a number between 1 and 100.");
userAnswer = Double.parseDouble(userInput);
if (userAnswer < 53) {
JOptionPane.showMessageDialog(null, "You picked a number LESS than the mystery number. Try again.");
} else if (userAnswer > 53) {
JOptionPane.showMessageDialog(null, "You picked a number GREATER than the mystery number. Try again.");
} else {
JOptionPane.showMessageDialog(null, "Congratulations! You just won 5 brownie points!");
}
}
// System.exit(0);
}
}
我不知道你想如何处理“胜利”,你可以在该比较中将 stillplaying
设置为 false
。
我还冒昧地在外部 while
循环中删除了与 true
的比较,因为它什么也不做。使用 lowerCamelCase => stillPlaying
命名变量也很常见,它只能称为 playing
,这是 boolean
游戏的一个相当常见的名称循环变量。
关于java - while 循环不打印消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33404655/