java - 在某些条件下无法打印正确的结果

标签 java

我创建了一个 Java 程序,它将用户输入作为整数数组,并打印该数组中的所有重复值及其索引。例如,用户输入 5 作为数组大小,然后输入 5 个数字,例如 1、1、1、1 和 1。程序应打印: Duplicate number: 1 Duplicate number's index: 1 Duplicate number: 1 Duplicate number's index : 2 重复号码: 1 重复号码的索引: 3 重复号码: 1 重复号码的索引: 4。如果没有重复项,程序将打印“无重复项” 程序按其应有的方式工作...除了打印“无重复项”即使有重复。

我尝试了很多事情,例如使用 boolean 标志(如果找到重复项,则为 true,然后打印结果),还将其设置为 false,插入更多 if 条件,将“无重复”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;
        }
    }
}

最佳答案

您有一个 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");
}

关于java - 在某些条件下无法打印正确的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57229084/

相关文章:

java - Sqlite-从两列中选择不同的

java - 更改运行 Eclipse 的 Java 版本

java.io.StreamCorruptedException : invalid stream header: 5B42403

java - IntelliJ 理念 : JUnit Test Class template depending on condition

java - Java 库仍有问题

java - 正则表达式匹配字符串的多个实例

java - 添加到 JFrame 的 JPanel 不执行任何操作

java - 如何停止悬吊线程池中的多个线程执行同一条语句?

java - 我的 STS 无法运行

java - 获取左上角监视器左上角位置的坐标