不等于do while循环

时间:2014-10-24 17:57:45

标签: java

由于某种原因,哨兵值无法按预期工作

public static int play() {
        String input;int result;
        do {
        input = JOptionPane.showInputDialog("Do you want to play-Enter 1 if yes , 0 if no");
        result = Integer.parseInt(input);
        } while (result != 1 || result != 0);
        return result;
    }

上面的代码永远不会有效但如果我将条件从while (result != 1 || result != 0);更改为while (result < 0 || result > 1);

,它就可以正常工作

为什么会这样,我如何在java的do...while循环中做不同的工作?

谢谢

2 个答案:

答案 0 :(得分:8)

使用:

while (result != 1 && result != 0) {...}

如果result不是01

,这将执行代码

在您的示例中,while循环中的布尔语句将始终等于true,因为结果只能等于1个值:

while (result != 0 || result != 1)

如果result1,则它不等于0,如果是0,那么它不能是1,所以它总是true

答案 1 :(得分:1)

while (result != 1 || result != 0)

这个条件意味着它总是循环,即使“1”或“0”作为回应:

如果用户输入0应该有效,则它将满足result != 1并返回true

如果用户输入1应该有效,则它将满足result != 0并返回true


您需要使用while (result != 1 && result != 0)

仅当答案不等于1且不等于0时才会循环。

相关问题