生成一个随机的4位数,并且每一位都不重复,用三种方法
------解决方案--------------------
http://sqlserver.iteye.com/blog/698651
------解决方案--------------------
- Java code
int[] array = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 }; int result = 0; Random random = new Random(); for (int i = 0, len = 8, index = 0; i < 4; i++) { index = random.nextInt(len); result = result * 10 + array[index]; array[index] = array[len-- + 1]; } System.out.println("result -> " + result);
------解决方案--------------------
我这个测试过的啦,没问题的
package com.gzsoft.zoom;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;
public class TestSIWEISHU {
public static void main(String[] args) {
Random rand=new Random();
List set=new ArrayList();
set.add(0);
for(int i=0;i<10;i++){
set.add(new Integer(i));
}
int beishu=1;
int result=0;
for(int i=0;i<4;i++){
int ranNum=rand.nextInt(9-i);
Integer in=(Integer) set.get(ranNum);
set.remove(in);
result+=in*beishu;
beishu=beishu*10;
if(i==2){
set.remove(new Integer(0));
}
}
System.out.print(result);
}
}