java - 相同的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;
}
解决方案
您的第二种情况有两个主要问题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 + " ");
}
应该管用。
推荐阅读
- docker - 在 docker 上运行的 jenkins 无法通过 localhost 访问
- unreal-engine4 - 在虚幻引擎 4 的编辑器小部件中获取游戏状态
- android - Android内部存储文件并发读写的安全性
- ruby-on-rails - WSL (Windows) 中的 Rails Dev 不断丢失 Ruby 版本
- python - 当没有产生该值时,有没有办法更新生成器循环条件?
- python - 由于多个用户帐户、python 版本和包管理器的干扰,python 配置存在缺陷。(未找到导入请求)
- apache-kafka - Quarkus 和 MicroProfile 是否支持 Confluent Schema Registry Avro Schema?
- csv - 在 Ubuntu 中用 NULL 替换空单元格
- github - 要求对拉取请求进行状态检查,然后在批准后部署该构建而不重新构建
- c# - 在容器类中处理 C# 事件的最佳方法是什么?