Java 中的非重复整数列表?任务

List of Non-Repeating Ints in Java? Assignment

我正在尝试创建一个包含 0 到 26 之间(因此在 1-25 范围内)的 20 个整数的列表,这些整数不会作为作业的一部分重复。我以为我已经弄明白了,但是程序一直在循环,没有结束。谁能帮帮我?

import java.util.Random;

public class prog433a
{
    public static void main(String args[])
    {
            Random r = new Random();

            int[] list = new int[20];

            for (int k = 0; k < list.length; k++)
            {
                boolean notADupe = false;

                while (notADupe == false)
                {
                    list[k] = r.nextInt(25) + 1;
                    for (int j = 0; j < list.length; j++)
                    {
                        if (list[j] == list [k] && j != k)
                        {
                            notADupe = true;
                        }
                        else
                        {
                            notADupe = false;
                            break;
                        }

                    }

                System.out.println(list[k]);
            }
        }
    }
}

编辑:这与另一个问题不同,因为我试图弄清楚如何使用允许我在作业中使用的方法(本质上,我已经在代码)。

我认为你已经扭转了局面。在 if 中,您应该将 notADup 设置为 false,而不是 true。但是,我会改为使用变量 isDup,并相应地更改 while 循环。

还有一个建议:您应该使用 while (!notADupe) 而不是 while (notADupe == false)。永远不要像那样比较布尔变量。有时可能会让您大吃一惊。

所以要解决您的问题,只需将您的 if-else 块更改为:

if (list[j] == list [k] && j != k) {
    notADupe = false;
    break;
} else {
    notADupe = true;
}

顺便说一句,您的解决方案有点复杂。对于每个元素,您都在遍历整个数组以查找重复项。相反,我建议您维护一个 Set<Integer> 存储已经看到的数字,并检查每个随机生成的数字。如果存在,跳过它并重新生成。

伪代码看起来像这样:

arr = []  // Your list array, initialize to size 20
seen = [] // A Set
for i from 1 -> arr.length
    num = rand.nextInt(25) + 1
    while seen contains num
        num = rand.nextInt(25) + 1
    seen.add(num)
    arr[i] = num