首页 > 解决方案 > 相同的while循环,但将条件放在while循环中并不能满足它的需要

问题描述

我有两个相同的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;
}

标签: java

解决方案


您的第二种情况有两个主要问题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 + " ");
}

应该管用。


推荐阅读