java - 如何从范围中排除零
问题描述
我正在学习 Java,处于初级阶段。我正在尝试打印骰子结果,所以从 1 到 6。
//instance of random class
Random DICE = new Random();
int DiceRange = 7;
int RIGHT = DICE.nextInt(DiceRange);
int LEFT = DICE.nextInt(DiceRange);
System.out.println("Right Dice = " + RIGHT);
System.out.println("Left Dice = " + LEFT);
此代码有时也会打印“零”的问题。我想保持范围从 1 到 6,而不是 0 到 6。我尝试执行以下操作,但没有奏效:
int i = 0;
while (DiceRange == 0); {
i++;
}
CPU 达到 100% :)
那么如何排除零呢?
解决方案
从随机文档:
public int nextInt(int bound)
返回介于 0(包括)和指定值(不包括)之间的伪随机、均匀分布的 int 值
因此,从您的代码开始,您可以使用以下方法解决您的问题:
Random DICE = new Random();
int DiceRange = 6;
int RIGHT = DICE.nextInt(DiceRange) + 1;
int LEFT = DICE.nextInt(DiceRange) + 1;
推荐阅读
- r - 无重复排列的遗传算法
- python - 附加列表字典时遇到问题
- sapui5 - SapUi5 在多行中逐行写入文本,而无需:
- c++ - 未能使用 get_accName 进行 MFC 控制
- wordpress - 我的 Wordpress 安装会在 EC2 停用后继续存在吗?
- android - 从 Chrome 调试移动应用程序 - 本地主机未解析
- aem - 可以增强 AEM 6.2 以支持 webp 吗?
- arrays - 尝试过滤二维数组并将它们推回谷歌表时发生错误
- elasticsearch - 您好,我正在尝试在我的节点 js 应用程序的弹性搜索中使用通配符查询和过滤器
- javascript - 无法读取减速器中未定义的属性“映射”