嵌套循环中的随机不同数字

Random distinct numbers in nested loop

我已经注册了 java 课程并完成了嵌套循环,但我正在尝试使用它并想制作不同随机数的列,但它向所有列打印 1 个数字。我怎样才能让它打印随机数到每个插槽(数字可以重复但不能像现在一样复制)

    Random rng = new Random();
    int chance = rng.nextInt((100)+1);
    for (int row = 0; row < 5; row ++) {
        System.out.print("row " + row + ": ");
        for (int col = 0; col < 10; col++) {
            System.out.print(chance + " ");
        }
        System.out.println();
    }

这是结果:

第 0 行:13 13 13 13 13 13 13 13 13 13

第 1 行:13 13 13 13 13 13 13 13 13 13

第 2 行:13 13 13 13 13 13 13 13 13 13

第 3 行:13 13 13 13 13 13 13 13 13 13

第 4 行:13 13 13 13 13 13 13 13 13 13

但我需要的是随机生成每个数字,而不是只滚动 1 个数字并将其放在各处。

你应该尝试这样的事情。 将 chance 变量放入循环内,每次都会提供一个新的随机数。

        Random rng = new Random();
        for (int row = 0; row < 5; row ++) {
            System.out.print("row " + row + ": ");
            for (int col = 0; col < 10; col++) {
                int chance = rng.nextInt((100)+1);
                System.out.print(chance + " ");
            }
            System.out.println();
        }

简单:

int chance = rng.nextInt((100)+1);

该行为您提供了一个新的随机数并将其分配给您的局部变量。

您的代码在 for 循环之前执行上述语句一次。然后你的循环打印你放入局部变量的内容。

如果您希望 "get me a random number" 重复发生,请考虑将其 移至 您的循环中。

仅此而已。