Java产生不重复随机数方法

 

public class TestRand3 {

    static int n = 20;
    static Random rand = new Random();
    static boolean[] bool = new boolean[n];

    public static void main(String[] args) {
        for (int j=0; j<n; j++) {
            int r = proRandom();
            System.out.print(r + " ");
        }
    }

    public static int proRandom() {
        int num =0;
        for (int i = 0; i<n; i++){
            do{
                num = rand.nextInt(n);   //如果产生的数相同继续循环
            }while(bool[num]);
            bool[num] =true;
            return num;
        }

        return n+1;

    }
}

 
如有疑问或问题,请联系邮箱 [email protected]

你可能感兴趣的:(java,随机数,不重复)