如何从[封闭的范围内排除零]

问题描述 投票:1回答:1
我从一开始就在学习Java。我正在尝试打印Dice结果,所以从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%:)

那么如何从中排除零?

java integer range dice
1个回答
2
投票
来自Random documentation

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;

© www.soinside.com 2019 - 2024. All rights reserved.