This question already has answers here:
Java generating non-repeating random numbers

(9个答案)


在8个月前关闭。





我不要重复的号码

该编码的输出是
17 32 81 84 40 44 11 51 67 17 92 27 10 17 6 67 2 32 56 58

重复数字17。

    int randomNum[] = new int[20];
    for(int i=0; i<randomNum.length; i++)
    {
        randomNum[i] = (int)(Math.random()*101)+0;
        System.out.print(" " + randomNum[i]);
    }


如何拒绝重复的号码并生成另一个号码?

最佳答案

您可以按照以下步骤进行操作:

public class Test {
    public static void main(String args[]) {
        int randomNum[] = new int[20];
        int lastRandom = 0;
        for(int i=0; i<randomNum.length; i++){
            int newRandom=(int)(Math.random()*101)+0;
            while(newRandom==lastRandom)
                newRandom=(int)(Math.random()*101)+0;
            lastRandom=newRandom;

            randomNum[i] = newRandom;
            System.out.print(" " + randomNum[i]);
        }
    }
}

09-30 14:13
查看更多