使用基本技术生成10个随机数而不重复 [英] Generating 10 random numbers without duplicate with fundamental techniques
本文介绍了使用基本技术生成10个随机数而不重复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我打算使用最简单的java(数组和循环)来生成没有重复的随机数...但是输出结果是10个重复数字,我不知道为什么.
my intend is to use simplest java (array and loops) to generate random numbers without duplicate...but the output turns out to be 10 repeating numbers, and I cannot figure out why.
这是我的代码:
int[] number = new int[10];
int count = 0;
int num;
while (count < number.length) {
num = r.nextInt(21);
boolean repeat = false;
do {
for (int i=0; i<number.length; i++) {
if (num == number[i]) {
repeat = true;
} else if (num != number[i] && i == count) {
number[count] = num;
count++;
repeat = true;
}
}
} while (!repeat);
}
for (int j = 0; j < number.length; j++) {
System.out.print(number[j] + " ");
}
推荐答案
如果满足两个条件之一,则需要从for
循环中退出break
.
You need to break
out of the for
loop if either of the conditions are met.
int[] number = new int[10];
int count=0;
int num;
Random r = new Random();
while(count<number.length){
num = r.nextInt(21);
boolean repeat=false;
do{
for(int i=0; i<number.length; i++){
if(num==number[i]){
repeat=true;
break;
}
else if(i==count){
number[count]=num;
count++;
repeat=true;
break;
}
}
}while(!repeat);
}
for(int j=0;j<number.length;j++){
System.out.print(number[j]+" ");
}
这将使您的代码正常工作,但@gonzo提出了更好的解决方案.
This will make YOUR code work but @gonzo proposed a better solution.
这篇关于使用基本技术生成10个随机数而不重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文