生成不重复的随机数字
public class UnrepeatRandomNumber
{
private int max;
private int min;
public UnrepeatRandomNumber()
{
this.max=10;
this.min=0;
}
public UnrepeatRandomNumber(int n1,int n2)
{
this();
if(n1<=n2)
{
this.max=n2;
this.min=n1;
}
else System.out.println("数据传入错误按照缺省值赋值");
}
public static void outArray(Integer[] integers)
{
for(int i=0;i<integers.length;i++)
System.out.println(integers[i]+" ");
System.out.println();
}
public Integer[] getRandomA(int length)
{
if(length<=0)
return new Integer[0];
else if(length>this.max-this.min)
{
System.out.println("长度只能在0到"+(this.max-this.min)+"范围内");
}
Random r1=new Random();
ArrayList resultList=new ArrayList();
while (resultList.size()<length)
{
Integer random=new Integer(this.min+r1.nextInt(this.max-this.min+1));
if(!resultList.contains(random))
resultList.add(random);
}
//将ArrayList强制转转程Integer对象;
return (Integer[])resultList.toArray(new Integer[0]);//toArray()方法要有參數,否则会出现错误
}
public static void main(String[]args)
{
outArray(new UnrepeatRandomNumber(2,100).getRandomA(98));
}
}
梦里不知身是客,一晌贪欢。