java - while 循环不打印消息

标签 java loops while-loop

该程序是一个游戏,用户必须猜测神奇的数字才能获胜。我是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 循环不仅不需要,而且还会破坏您的程序。两种情况,userAnswer53 或不是。让我们检查一下这两种情况。

不等于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/

相关文章:

java - 列表删除方法是原始的

Java:写 Supertype a = new Subtyp()` 的原因是什么?

javascript - 如何使用 jquery $.grep 解决 jshint 错误 `Don' t makefunctions inside a loop.`

iOS:在 while 循环中使用 block 回调的异步方法

c - while循环不执行

c - 循环使用 while

java - 如何显示html :text using <logic:iterate> for List<String> in Struts1. 1

java - RESTEasy 客户端异常处理

java - 需要从以下结果集中按以下方式形成 JSON 响应

python - python 中的循环优化