我正在生成 1-54 范围内的 6 个整数的数组(类似于乐透号码)。但是,当尝试检测重复项时,我的代码没有执行。如果我的条件逻辑会捕获重复项,我尝试通过简单地打印“我们已经找到重复项”来进行调试。当然,它不会打印所需的输出:
18-33-39-41-41-45
我想检测重复项,以便生成另一个不等于发现的重复项的随机数。我不想仅仅为了获得另一个数字而增加/减少副本的值,我想实际生成另一个介于 1 和 54 之间且不等于副本的值。
这是我的代码:
public class Main {
public static void main(String[] args) {
Random rand = new Random();
int[] luckyArray = new int[6];
//build array
for (int i = 0; i < luckyArray.length; i++) {
int luckyNumber = rand.nextInt(54) + 1;
luckyArray[i] = luckyNumber;
}
//detect duplicates in the array
for (int i = 0; i < luckyArray.length; i++) {
if (i > 0 && luckyArray[i] == luckyArray[i - 1]) {
System.out.print("WE HAVE FOUND A DUPLICATE!");
/* while (luckyArray[i - 1] == luckyArray[i]) {
luckyArray[i] = rand.nextInt(54) + 1;
}*/
}
}
//sort the array before printing
Arrays.sort(luckyArray);
for (int t = 0; t < luckyArray.length; t++) {
if (t != 5) {
System.out.print(luckyArray[t] + "-");
} else System.out.print(luckyArray[t]);
}
}
}
我希望将当前索引 [i]
与其之前的索引 [i-1]
进行比较,如果/当它们相等时,为当前索引。
提前致谢!
最佳答案
我(个人)会在这里依靠 Set
的属性来确保您根本不会保留重复项 - 您甚至不必检查是否有重复项:
Random rand = new Random();
int numNumsToGenerate = 6;
Set<Integer> luckySet = new HashSet<Integer>();
//build set
while (luckySet.size() < numNumsToGenerate) {
luckySet.add(rand.nextInt(54) + 1);
}
一旦你建立了你的集合,你就可以通过使用你的集合
的内容创建一个新的列表
来对它们进行排序:
//sort the array before printing
List<Integer> luckyList = new ArrayList<Integer>(luckySet);
Collections.sort(luckyList);
关于java - 生成随机数数组并替换重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32640867/