【发布时间】:2015-04-01 06:33:24
【问题描述】:
概述: 我的程序必须在一个数组中存储从 1 到 100 范围内的 20 个非重复随机生成的数字。 问题: 如果我在内部 for 循环中找到匹配项(重复的 #),我会标记布尔变量。这是我不知道该怎么做。在for循环之后,如果没有标记布尔值,我想将随机数添加到数组中。我还想增加 x(直到我存储了 20 个非重复数字),但前提是我将元素添加到数组中。
public void duplication(){
int max = 100; // max value for range
int min = 1; // min value for range
boolean duplicate = false;
Random rand = new Random();
for (int x = 0; x < 20; x++){
//initiates array that stores 20 values
int[] all = new int[20];
//generates # from 1-100
int randomNum = rand.nextInt((max - min) + 1) + min;
all[x] = randomNum;
//iterates through array
for (int i : all) {
//if there's a match (duplicate) flag boolean
if (i == randomNum){
duplicate = true;
}
else {
duplicate = false;
}
}
}
//if boolean hasn't been flagged
if (duplicate=false){
//store to array
}
}
【问题讨论】:
-
注意:
if (duplicate=false)应该是if(!duplicate)(或者使用==代替,但不推荐使用)。 -
考虑到您只需要 20 个数字这一事实,我建议您使用
HashSet并在条件while hashSet.size()<=20下添加数字 -
@TheLostMind 同意 -
Set绝对是解决这个问题的好容器。 -
@TheLostMind 我需要使用一个数组。也许,有人可以同时使用 HashSet 和数组来提供正确的解决方案,以便为观众提供更多选择。
-
@Alnitak - 减少代码的混乱。 :)(虽然会影响时间和空间的复杂性)
标签: java arrays random boolean