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

程序打印出不需要的重复结果

程序打印出不需要的重复结果

肥皂起泡泡 2023-04-26 10:47:07
我创建了一个 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但是,程序打印: 重复数字:1 重复数字索引:1 重复数字:1 重复数字索引:2 重复数字:1 重复数字索引:3 重复数字:1 重复数字索引:4 重复数字:1 重复数字索引:2重复数:1 重复数索引:3 重复数:1 重复数索引:4 重复数:1 重复数索引:3 重复数:1 重复数索引:4 重复数:1 重复数索引:4我尝试调试程序,得到的结论是,因为打印结果是在循环内的,只要循环运行并满足一定的条件,就会有多次打印。但是,我找不到使代码不同的方法,因此只打印正确数量的结果。我试图调整代码:插入 break 和 continue,将 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.println("Please enter your array values: ");             for (i = 0; i < arraySize; i++) {        arrayList[i] = sc.nextInt();  }    for (i = 0; i < arrayList.length; i++)  {        for (j = i + 1; j < arrayList.length; j++)  {                        if (i!=j && arrayList[i] == arrayList[j])   {                System.out.println("Duplicate number: " + arrayList[i]);                                                  System.out.println("Duplicate number's index: " + j); }             else if (i!=j && arrayList[i] != arrayList[j])  {System.out.println("There are no duplicates");  }        }     }
查看完整描述

1 回答

?
眼眸繁星

TA贡献1873条经验 获得超9个赞

您正在做的是找到重复项的重复项。取 1,1,1。首先,您在索引 1 和 2 处找到 1、索引 0 的两个副本。然后您在索引 2 处找到 1、索引 1 的副本。有多种解决方案。

  1. 跟踪遇到的重复项。如果一个已经被外循环处理过,就不要再处理了。您可以通过单独放置list找到的重复项并使用该contains方法检查它是否存在来做到这一点。

  2. 对列表进行排序,然后查找重复序列。这改变了位置,所以它可能不是你想要的。

  3. 找到重复项后将其删除。这也会改变位置,因此它可能也不是您想要的。我还增加了一些额外的复杂性。

你也有不同的问题。

  1. 当遇到重复项时,您还会打印出没有找到重复项,这看起来很矛盾。要解决此问题,请使用标志boolean并在找到重复项时将其设置为 false,并在退出循环时使用它来打印消息。

  2. 因为你开始你的内部循环比外部循环多一个(即j = 0 and i = j+1)它们永远不会相同。所以你不需要测试(i!=j)。此外,外循环的终止应该是arrayList.length-1.


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

添加回答

举报

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