【问题标题】:Array[index + 1] causing the program FATAL error [duplicate]Array[index + 1] 导致程序致命错误 [重复]
【发布时间】:2016-12-31 15:29:59
【问题描述】:

我有整数计数,这是我的数组索引,假设计数等于 5,所以我的 arrayWeight[count] 索引/计数等于 5。 数组中的值是双精度的,数组中的所有 5 个单元格都被使用并包含值。

现在我愿意将所有arrayWeight[] 值添加到DataPoint[] 数组中,尽管DataPoint[] 中的索引等于6(计数+ 1)。 并且数组中的第六个索引在循环之外使用,如下所示:

    double[] arrayWeight = new double[count]; // Array of user weight
    DataPoint[] dp = new DataPoint[count+1];
        for (int i = 0; i < count; i++) { // Array weight is inserted into datapoints y and i is the x so the graph will follow the (x,y)
            dp[i] = new DataPoint(i, arrayWeight[i]);
            Log.d("ArrayWeight", "equals: " + arrayWeight[i]);
            Log.d("Array", "equals: " + i);
        }
    dp[count+1] = new DataPoint(count+1, db.getDetails().getWeight());
    return dp;

我可以告诉你,当我从索引中删除 +1 并仅使用 count 时,代码正在运行,但我需要使用 count + 1 以便可以向 DataPoint[] 数组添加另一个值。

错误信息:

E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.none.myapplication, PID: 12760
java.lang.RuntimeException: Unable to start activity   
ComponentInfo{com.none.myapplication/com.none.myapplication.MainActivity}:  
java.lang.ArrayIndexOutOfBoundsException: length=6; index=6

如何正确创建array[index+1],才不会返回致命错误?

【问题讨论】:

  • 你的数组去0-5意思是6元素,所以你的数组中的最大位置是5而不是6
  • 为什么你认为等于数组长度(或“大小”)的数字是有效索引?
  • @PavneetSingh 我在循环之后添加第六个元素。
  • 您的数组DataPoint[] dp = new DataPoint[count+1]; 的大小为count+1,因此其最大索引为count,但在dp[count+1] = new DataPoint(count+1, db.getDetails().getWeight()); 中,您尝试使用超出[0, count] 范围的索引。
  • @Tom 那我该怎么写呢?

标签: java android arrays


【解决方案1】:

您应该在此行中使用dp[count] insted of dp[count+1]:

dp[count+1] = new DataPoint(count+1, db.getDetails().getWeight());

因为 dp 中的索引将是 0 计数

【讨论】:

    【解决方案2】:

    索引应该是count 而不是count + 1。 for 循环中的最后一个索引是count - 1。看到循环是i &lt; count

    【讨论】:

      【解决方案3】:

      dp[count+1] 在您的代码中无效。数组索引从 0 开始,所以如果你的 count=5,count+1 = 6。所以 dp 的长度是 6,但索引从 0 到 5 开始。

      你应该在你的 for 循环之后执行 dp[count] 来解决这个问题。

      【讨论】:

        【解决方案4】:

        数组dpcount + 1 索引,所以最高索引是count(因为第一个是零)。 替换

        dp[count+1] = new DataPoint(count+1, db.getDetails().getWeight());
        

        dp[count] = new DataPoint(count, db.getDetails().getWeight());
        

        解决您的问题。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多