我试图创建一个简单的彩票程序。这是一个问题:它仍然打印相同的数字。例如,我将 33 21 8 29 21 10 作为输出。每次生成随机数时,代码都会检查该数字是否已经生成,然后它会创建一个新的随机数,但之后不会再次检查。我找不到办法做到这一点。

public static void main(String[] args)
{

    int[] lottery = new int[6];
    int randomNum;

    for (int i = 0; i < 6; i++)
    {
        randomNum = (int) (Math.random() * 50); //Random number created here.
        for (int x = 0; x < i; x++)
        {
            if (lottery[i] == randomNum) // Here, code checks if same random number generated before.
            {
                randomNum = (int) (Math.random() * 50);//If random number is same, another number generated.
            }

        }
        lottery[i] = randomNum;
    }

    for (int i = 0; i < lottery.length; i++)
        System.out.print(lottery[i] + " ");

}

最佳答案

您的代码有两个问题:

  • 你检查lottery[i]randomNum是否相同,应该是lottery[x]
  • 当你重新生成一个随机数时,你不会根据 lottery 中的第一个数字来检查它。

  • 这是一个更正的版本:
    public static void main(String[] args) {
    
        int[] lottery = new int[6];
        int randomNum;
    
        for (int i = 0; i < 6; i++) {
            randomNum = (int) (Math.random() * 50); // Random number created here.
            for (int x = 0; x < i; x++) {
                if (lottery[x] == randomNum) // Here, code checks if same random number generated before.
                {
                    randomNum = (int) (Math.random() * 50);// If random number is same, another number generated.
                    x = -1; // restart the loop
                }
    
            }
            lottery[i] = randomNum;
        }
    
        for (int i = 0; i < lottery.length; i++)
            System.out.print(lottery[i] + " ");
    
    }
    

    10-08 19:17