Spe*_*edo 2 java arrays random boolean
概述:我的程序必须在数组中存储20个非重复的随机生成的数字,范围为1到100.问题:如果我在内部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
}
}
Run Code Online (Sandbox Code Playgroud)
这将为您提供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));
}
Run Code Online (Sandbox Code Playgroud)
O/P:
[68, 69, 64, 65, 66, 67, 47, 74, 14, 17, 16, 21, 81, 54, 52, 82, 59, 57, 63, 88]
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
697 次 |
最近记录: |