在过去的几个小时里,我一直在尝试编写奶牛和公牛程序。在母牛和公牛中。该程序应该生成 4 个介于 0 和 9 之间的非重复整数供用户猜测,但我的程序输出了一组整数,其中有一些重复值大约为 1 次 10 次。我去过的每个人都没有发现任何错误,如果您知道修复方法,请帮助我。到目前为止我的程序如下:
Random rng = new Random();
int pos1 = rng.nextInt(10);
int pos2 = rng.nextInt(10);
int pos3 = rng.nextInt(10);
int pos4 = rng.nextInt(10);
int norepeat = 0;
while(norepeat == 0){
if(pos1 == pos3 || pos1 == pos2 || pos1 == pos4){
pos4 = rng.nextInt(10);
}
if(pos2 == pos1 || pos2 == pos3 || pos2 == pos4){
pos2 = rng.nextInt(10);
}
if(pos3 == pos1 || pos3 == pos2 || pos3 == pos4){
pos3 = rng.nextInt(10);
}
if(pos4 == pos3 || pos4 == pos2 || pos4 == pos1){
pos4 = rng.nextInt(10);
}
else {
norepeat = 1;
}
}
System.out.print(pos1);
System.out.print(" " + pos2);
System.out.print(" " + pos3);
System.out.print(" " + pos4);
最佳答案
这是我要做的。运行此代码后,您将获得一组四个不同的整数,范围为 0-9。
Random rng = new Random();
Set<Integer> numbersFound = new HashSet<>();
while(numbersFound.size() < 4) {
numbersFound.add(rng.nextInt(10));
}
这是有效的,因为 Set
接口(interface)的实现强制唯一性。向集合中添加一个数字,当它已经存在时,没有任何效果。
关于java - 母牛和公牛重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39925189/