随机取数比较简单,有很多的方法可以做,这里介绍其中一种。
这个方法时间复杂度较小。
要注意一些细节
public class Stochastic {
public static void main(String[] args) {
// TODO Auto-generated method stub
int i,j;
String n,h="";
int[] s=new int[10];
for(i=0;i<s.length;i++){
j=(int)(Math.random()*100); //随机取出0~100的数,random()返回一个0~1的double随机数
if(i==0){
s[i]=j;
h=h+j+" ";
continue; //结束本次循环,回到循环条件,继续判断是否执行下一次循环
}
n=""+j;
while( h.indexOf(n)!=-1){ //indexOf(String s)返回当前串中首次与s串匹配子串的序号,如果未找到返回-1
j=(int)(Math.random()*100);
n=""+j;
}
h=h+n+" ";
s[i]=j;
}
for(i=0;i<s.length;i++)
System.out.println(s[i]);
}
}
运行结果:
76
41
37
50
93
2
94
56
59
13