为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

牛魔王的故事 2023-04-26 10:48:38
我创建了一个 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. 如果没有重复,程序打印“无重复” 该程序正常工作......除了它打印“无重复”即使有重复。我尝试了很多事情,例如使用布尔标志(如果找到重复项,则为真,然后打印结果),还将其设置为假,插入更多 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;        }    }}
查看完整描述

1 回答

?
慕婉清6462132

TA贡献1804条经验 获得超2个赞

您有一个duplicates标志,您将其初始化为,但在有重复项时false从不设置为。假设你在循环之后true有一个简单的(如果你不需要的话),它应该看起来像iffor


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");

}


查看完整回答
反对 回复 2023-04-26
  • 1 回答
  • 0 关注
  • 77 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信