如何修复我的重复检测代码? Java

How do I fix my duplicate detection code? Java

我这里有一台扫描仪,可以收集一系列数字。我希望它在每次用户输入数字时扫描列表,因此如果用户输入的数字已经在列表中,则新输入将为 disregarded/ignored 并且同时不向循环添加增量。

问题是代码似乎无法识别重复项。即使尝试了几次,它仍然继续注册重复的号码。

到目前为止我的代码:

public class Number {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("How Many Numbers You want to Enter:");
        int n = input.nextInt();
        
        List<Integer> number = new ArrayList<>();
        
        for(int s=0;s<n;s++) {
            int t = input.nextInt();
            for (int j = 1; j < number.size(); j++) {
                if (t == number.get(j)) {
                    System.out.print("Duplicate!");
                    s--;
                    continue;
                } else {
                    number.add(t);
                }
            }            
        }
    }
}

目前号码列表中没有保存任何东西,所以首先要做的是添加调试以找出原因,或者更好的是,我们可以使用 ArrayList.contains(...) 方法来无需导致问题的嵌套循环即可轻松解决此问题,例如以下工作:

for(int s=0;s<n;s++) {
    int t = input.nextInt();
    if(number.contains(t)){
        System.out.print("Duplicate!\r\n");
        s--;
        continue;
    } else {
        number.add(t);
    }          
}
//Print the result
System.out.println(Arrays.deepToString(number.toArray()));

长度为 5 且此数字序列 2,3,7,3,5,1 的输出为:

How Many Numbers You want to Enter:5
2
3
7
3
Duplicate!
5
1
[2, 3, 7, 5, 1]