概述: 我的程序必须在数组中存储 20 个从 1 到 100 范围内随机生成的非重复数字。 问题: 如果我在内部 for 循环中找到匹配项(重复的 #),我会标记 boolean 变量。这是我不知道该怎么做。在 for 循环之后,如果 boolean 值尚未被标记,我想将随机数添加到数组中。我还想增加 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
}
}
最佳答案
这将为您提供一个 0 到 100 之间的随机整数数组
public static void main(String[] args) {
Set<Integer> s = new HashSet<Integer>(); // create a set
Random r = new Random();
while (s.size() < 20) {
s.add(r.nextInt(100)+1); // add elements to set upto size =20
}
Integer[] array = new Integer[20];
s.toArray(array); // convert set to array of Integers
System.out.println(Arrays.toString(array));
}
操作:
[68, 69, 64, 65, 66, 67, 47, 74, 14, 17, 16, 21, 81, 54, 52, 82, 59, 57, 63, 88]
关于java - 将不重复的数字存储在数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28275607/