Java 在某些情况下无法打印正确的结果

Java 在某些情况下无法打印正确的结果,java,Java,我创建了一个Java程序,它将用户输入作为一个整数数组,并打印该数组中的任何重复值及其索引。例如,用户输入5作为数组大小,然后输入5个数字,例如1、1、1、1和1。程序应打印:重复编号:1重复编号索引:1重复编号:1重复编号索引:2重复编号:1重复编号索引:3重复编号:1重复编号索引:4。如果没有重复项,程序将打印“无重复项”程序将正常工作…除非即使存在重复项,它也会打印“无重复项” 我尝试了很多方法,例如使用布尔标志(如果找到重复项,则为true,然后为print result),还将其设置为

我创建了一个Java程序,它将用户输入作为一个整数数组,并打印该数组中的任何重复值及其索引。例如,用户输入5作为数组大小,然后输入5个数字,例如1、1、1、1和1。程序应打印:重复编号:1重复编号索引:1重复编号:1重复编号索引:2重复编号:1重复编号索引:3重复编号:1重复编号索引:4。如果没有重复项,程序将打印“无重复项”程序将正常工作…除非即使存在重复项,它也会打印“无重复项”

我尝试了很多方法,例如使用布尔标志(如果找到重复项,则为true,然后为print result),还将其设置为false,插入更多的if条件,将“no duplicates”(无重复项)print.out放在花括号内的不同位置,但没有任何效果。如果我把“无重复”print.out放在循环之外,那么即使有重复,它也会打印。如果我将“无重复项”print.out作为“无重复项找到条件”的一部分,则会打印出多个“无重复项”,因为它是循环的一部分。我尝试过调试,但看不出代码的问题在哪里。请帮忙

Scanner sc = new Scanner(System.in);
int i, j;
System.out.println("This program lets you enter an array of numbers, and then tells you if any of the numbers "
        + "are duplices, and what the duplicates' indices are. \nPlease enter your desired array size: ");
int arraySize = sc.nextInt();
while (arraySize <= 0) {
    System.out.println(arraySize + " is not a valid number. \nPlease enter your desired array size: ");
    arraySize = sc.nextInt();
    continue;
}
int[] arrayList = new int[arraySize];
System.out.print("Please enter your array values: ");
for (i = 0; i < arraySize; i++) {
    arrayList[i] = sc.nextInt();
}
boolean duplicates = false;
for (i = 0; i < arrayList.length - 1; i++) {
    for (j = i + 1; j < arrayList.length; j++) {
        if (arrayList[i] == arrayList[j]) {
            System.out.println("Duplicate number: " + arrayList[i]);
            System.out.println("Duplicate number's index: " + j);
            break;
        }
    }
}
Scanner sc=新扫描仪(System.in);
int i,j;
System.out.println(“此程序允许您输入数字数组,然后告诉您是否有任何数字”
+是重复的,重复的索引是什么。\n请输入所需的数组大小:”;
int arraySize=sc.nextInt();

while(arraySize您有一个
duplicates
标志,您可以将其初始化为
false
,但当存在重复项时,决不能将其设置为
true
。假设在
for
循环之后有一个简单的
if
(如果您不需要),它应该看起来像

boolean duplicates = false;
for (i = 0; i < arrayList.length - 1; i++) {
    for (j = i + 1; j < arrayList.length; j++) {
        if (arrayList[i] == arrayList[j]) {
            duplicates = true; // <-- Add this.
            System.out.println("Duplicate number: " + arrayList[i]);
            System.out.println("Duplicate number's index: " + j);
            break;
        }
    }
}
if (!duplicates) {
    System.out.println("no duplicates");
}
boolean duplicates=false;
对于(i=0;iduplicates=true;//成功了!在我的一次尝试中,我实际上在if语句中已将flag设置为true,但没有在最后包含!duplicates条件。我今天学习了好的java:)