随即生成不重复的数!

luozhangwen 2010-04-24 06:19:29

package com.lzw.test;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class UnSeqRandomNumber {
private int min;
private int max;

public UnSeqRandomNumber() {
this.min = 0;
this.max = 10;
}

public UnSeqRandomNumber(int min, int max) {
this();
if (max > min) {
this.min = min;
this.max = max;
} else
System.out.println("max比min小,按默认的值生成UnrepeatRandomMumber对象!");
}

// 第一种方法:排除法.随机生成数字,如果是新生成的数字则放到结果集中
// 否则不采取行动
public Integer[] getRandomA(int length) {
if (length <= 0) {
System.out.println("数字长度小");
return new Integer[0];
} else if (length > (this.max - this.min)) {
System.out.println("结果列表长度达不到要求:" + length + "结果只能是:"
+ (this.max - this.min));
length = this.max - this.min;
}
Random rand = new Random();
List<Integer> list = new ArrayList<Integer>();
while (list.size() < length) {
Integer randnum = new Integer(this.min
+ rand.nextInt(this.max - this.min + 1));
if (!list.contains(randnum)) {
list.add(randnum);
}
}
return (Integer[]) list.toArray(new Integer[0]);
}

public static void outputArray(Integer[] array) {
if (array != null) {
for (int i = 0; i < array.length; i++) {
System.out.println(array[i] + " ");
}
}
System.out.println();
}

public static void main(String[] args) {
// TODO Auto-generated method stub
UnSeqRandomNumber test = new UnSeqRandomNumber(5, 35);
outputArray(test.getRandomA(100));
}

}

...全文
98 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

23,404

社区成员

发帖
与我相关
我的任务
社区描述
Java 非技术区
社区管理员
  • 非技术区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧