【问题标题】:Snippet of 1 Array to Check for Recurring Elements [duplicate]用于检查重复元素的 1 个数组的片段 [重复]
【发布时间】:2017-07-24 20:31:54
【问题描述】:

我正在研究仅使用 1 个数组和一个嵌套的 for 循环来检查重复的元素并将它们转为 0。我遇到了 IndexBound 问题,无法完全判断出了什么问题。

有什么帮助吗?

    int data[] = new int[20];
    for(int i = 0; i < data.length; i++) {
        data[i] = in.nextInt();
    }
    for (int i = 0; i < 18; i++) {
        for (int x = i + 1; x < 20; i++) {
            if (data[i] == data[x]) {
                data[x] = 0;
            }
        }
    }


Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 20
at Arrays.Prog415h.main(Prog415h.java:47)
if (data[i] == data[x]) {

【问题讨论】:

  • in 是扫描仪吗?
  • @UnknowableIneffible 是的

标签: java arrays eclipse indexoutofboundsexception


【解决方案1】:

这里,嵌套for循环的增量是i而不是x。这意味着i 在外部和内部循环的每次迭代中都超出了数组边界。要解决此问题,请将其更改为:

for (int x = i + 1; x < 20; x++)

【讨论】:

  • 好的,这只是我的错字。
猜你喜欢
  • 2018-09-17
  • 2016-08-06
  • 1970-01-01
  • 1970-01-01
  • 2018-03-21
  • 2018-04-06
  • 2015-03-26
  • 2014-08-25
  • 2015-03-13
相关资源
最近更新 更多