相同的while循环,但是将条件放入while循环中并不能满足需要

时间:2020-05-12 19:18:03

标签: java

我有两个相同的while循环,逻辑很简单。如果值为7或参数,则应停止。可以使用以下方法

while(true) {
    int value = diceRoll();
    if(value ==7 || value == point){
        return value;

    }
    System.out.print(value + " ");
}

但是使用下面的方法,它并不能满足需要。但这与上述方法几乎相同。

public static int secondStage(int point) {
    int x = 0;
    while((diceRoll() != 7) || (diceRoll() != point)) {
        System.out.print(diceRoll() + " ");
        x= diceRoll();
    }
    return x;
}

2 个答案:

答案 0 :(得分:1)

您的第二个while状况有两个主要问题。

  1. 您应该使用and运算符,而不是or 布尔表达式以正确评估。
  2. 包含diceRoll()的代码行太多。你可以实现 在给定的迭代中只需调用一次即可达到目的。

替换您的while条件

while((diceRoll() != 7) || (diceRoll() != point))

使用

while(x != 7 && x != point)

总体

while(x != 7 && x != point) {
   x = diceRoll();
   System.out.print(x + " ");
}

应该工作。

答案 1 :(得分:0)

我第二个@DavidZimmerman的评论。

while条件中有多个diceRoll调用可能会产生一些严重的逻辑错误。这些调用中的每一个都有可能获得不同的结果,因此您的where子句根本不会保持一致。

要添加到@VHS的答案:

  1. 像在上一个代码块中一样初始化变量
int x = 0;
  1. 像这样,将diceRoll从where子句中取出并调用diceRoll():
where (x != 7 && x != point) {
    // do work
    x = diceRoll();
}
相关问题