我有一个脚本
的困境我想做一个 Bingo 游戏,在这里我会使用这个Math.random
脚本
public class Bingo{
public static void main(String[]args){
int num = (int) (Math.random() *(75)) +1;
int x = 0;
while(x==0){
System.out.println(num +"\n");
}
}
}
在这种情况下,我的输出始终为 34
有没有办法让我的输出总是一个不同的数字?谢谢!
答案 0 :(得分:3)
首先使用Math.random()
会提供浮动点值。 不建议将其用于随机整数生成。所以我会在这里使用random.nextInt()
。
其次,当set
点击break
的{{1}}时,您需要size
来维护之前生成的数字和set
循环。如果你已经生成了这个数字,你可以75
循环。
以下是代码。
continue
进口:
int num = 0;
Random r = new Random();
Set<Integer> set = new HashSet<>();
while (set.size() < 75) {
num = r.nextInt(75) + 1;
if (set.contains(num))
continue;
set.add(num);
System.out.println(num + "\n");
}
答案 1 :(得分:1)
根据您只需绘制一次的每个数字,您必须选择不同的方法。我会将所有球添加到列表中,然后shuffle the list。然后你可以迭代球(当赢得比赛时可能break
):
final List<Integer> balls = new ArrayList<>();
for (int i = 0; i <= 75; i++) {
balls.add(i);
}
Collections.shuffle(balls);
for (int ball : balls) {
System.out.println(ball); //or whatever your logic is
}
进口:
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
答案 2 :(得分:0)
您的num
始终具有相同的值,因为您在循环中没有更改它。
尝试类似:
/* your code here */
while (x==0) {
num = (int) (Math.random() *(75)) +1;
System.out.println(num);
}
答案 3 :(得分:0)
更改为
public class Bingo {
public static void main(String[] args) {
int x = 0;
while (x == 0) {
int num = (int) (Math.random() * (75)) + 1;
System.out.println(num + "\n");
}
}
}
答案 4 :(得分:0)
为什么不使用以下代码:
Random random = new Random();
int randomNumber = random.nextInt(max + 1 - min) + min;
其中max为75,min为0.此外,两个数字都包含在内。请注意,数学随机的内部算法使用Leniar同余发生器(虽然不是最好的),但考虑到你将使用64位机器,数字不应该很快重复。