日期:2014-05-20 浏览次数:20649 次
import java.util.Random; import java.util.Vector; public class GetNum { private Vector<Integer> nums = null; private Random random = null; public GetNum() { nums = new Vector<Integer>(10); for (int i = 0; i < 10; i++) { nums.add(i); } random = new Random(); } public Vector<Integer> getNum() { Vector<Integer> temp = new Vector<Integer>(5); for (int i = 0; i < 5; i++) { Integer integer = nums.get(random.nextInt(nums.size())); temp.add(integer); nums.remove(integer); } return temp; } public static void main(String... args) { GetNum num = new GetNum(); System.out.println(num.getNum()); } }
------解决方案--------------------
Random random = new Random(); Set<Integer> s = new HashSet<Integer>(); while(true){ int temp = random.nextInt(9); s.add(temp); if(s.size()==5) break; } for (Integer integer : s) { System.out.println(integer); }
------解决方案--------------------
支持1楼的第2种方法,很佩服这想法
------解决方案--------------------
http://topic.csdn.net/u/20111012/14/11b025f0-e55a-4db7-bcb8-14f312fbaa06.html
看4楼的
------解决方案--------------------
Random r=new Random();
Set<Integer> set=new HashSet<Integer>();
whiel(set.size<6){
int count=r.nextInt(9);
set.add(count);
}
for(int count:set){
System.out.println(count);
}
------解决方案--------------------
0 =< nextInt(n) < n
------解决方案--------------------
方法一:
public List getRandomNumber(){ List all=new ArrayList(); for(int i=0;i<10;i++)all.add(i);//先放10个数到一个集合中 List num=new ArrayList(); for(int i=0;i<5;i++){ //获取5次 int index=(int)(Math.random()*(10-i));//每次产生一个随机索引 num.add(all.get(index));//获取索引处元素放置到num集合中 all.remove(index);//删除刚才已经获取的元素 //注意每删除一个all集合中少一个元素,索引范围会缩小 } return num; }
------解决方案--------------------
int a[]={0,1,2,3,4,5,6,7,8,9}
for(int i=0;i<5;i++){
nextInt(a.length-1)
}
------解决方案--------------------
public class RandomNumber { public static void main(String[] args) { List<Integer> list=new ArrayList<Integer>(); Random roand= new Random(); int i=0; while(i<5) { int num= roand.nextInt(10); if(!list.contains(num)) { list.add(num); i++; } } for(int j=0;j<list.size();j++) { System.out.println(list.get(j)); } } }