-4

I have integer count which is my array index, lets assume count is equal to 5, so my arrayWeight[count] index/count is equal to 5. The values inside the array are doubles and all the 5 cells in the array are used and contains values.

Now I'm willing to add all the arrayWeight[] values into DataPoint[] array, though the index in DataPoint[] is equal to 6 (count + 1). and the sixth index in the array is used outside of the loop as you can see below:

    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;

I can tell you the code is working when I remove the +1 from the index and use only count, but I need to use count + 1 so I can add another value to DataPoint[] array.

Error message:

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

How to create array[index+1] in the correct way, so it wont return fatal error?

Yotam Dahan
  • 689
  • 1
  • 9
  • 33

4 Answers4

0

You should use dp[count] insted of dp[count+1] in this line:

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

because indices in dp will be 0 to count

0

The index should be count instead of count + 1. The last index in the for loop was count - 1. See that the loop is i < count.

Shakhar
  • 432
  • 3
  • 12
0

dp[count+1] is not valid in your code. Array indexes start from 0, so if your count=5, count+1 = 6. So length of dp is 6, but indexes start from 0 to 5.

You should do dp[count] after your for loop to fix this.

Alucard
  • 37
  • 1
  • 4
0

Array dp has count + 1 indices, so the highest index is count (Because first is zero). Replace

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

with

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

to fix your problem.

J. Tennié
  • 348
  • 2
  • 6