我有两个相同的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;
}
答案 0 :(得分:1)
您的第二个while
状况有两个主要问题。
and
运算符,而不是or
布尔表达式以正确评估。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的答案:
int x = 0;
where (x != 7 && x != point) {
// do work
x = diceRoll();
}