PatGreens
PatGreens

Reputation: 139

ArrayIndexOutOfBoundsException while finding the maximum difference between two consecutive elements in array

I cannot find a logistic algorithm to find the maximum difference between two consecutive indexes in an array. When I used the method in my code, my client page gave me an error saying I have an outofbounds Exception. Any suggestions? If you need more code then just ask.

//method returning the largest change between two consecutive days
    public int NetChange()
    {
      int BiggestNet = temps[0] - temps[1];
      for( int i = 0; i < temps.length; i++ )
      {
         if( (temps[i] - temps[i+1]) > BiggestNet )
         {
            BiggestNet = (temps[i] - temps[i+1]);
         }
      }
      return BiggestNet;
     } 

Error:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10
    at Forecast.NetChange(Forecast.java:105)
    at Forecast.toString(Forecast.java:120)
    at ForecastClient.main(ForecastClient.java:12

Upvotes: 0

Views: 342

Answers (4)

Buddha
Buddha

Reputation: 4476

Issue is with these two pieces of code... i < temps.length and temps[i+1]

When i is equal to temps.length -1 which is last iteration of the loop, i+1 will be equal to temps.length. It means you are trying to access array[10] when the array has 10 elements. But array only contains 0 to 9 as index.

changing i < temps.length to i < temps.length-1 will fix the issue..

Upvotes: 3

Nathua
Nathua

Reputation: 8836

temps[i+1] is the issue

when i is the last index, i+1 will give exception.

Upvotes: 1

Christian Tapia
Christian Tapia

Reputation: 34166

Since your loop variable i goes from 0 to temps.length - 1 (because of <) and you have in the body

temps[i+1]

when i takes the value of temps.length - 1 (the last value it can take), when you reach

temps[temps.length - 1 + 1]

is the same of

temps[temps.length]

it will raise an Excepction, since an array can only be accessed from 0 to length - 1.

How to solve this? You could try decreasing the last value of i in 1. In other words:

for(int i = 0; i < temps.length - 1; i++)

Upvotes: 1

C.B.
C.B.

Reputation: 8336

Change

for( int i = 0; i < temps.length; i++ )

To

for( int i = 0; i < temps.length - 1; i++ )

temps.length will give you the length of the array not using zero based counting, but it is accessed by zero based indicies. So if i = temps.length - 1, that is actually the last element in the array. If you then try to access temps[i+1] that will be longer than your array and thus out of bounds.

Upvotes: 2

Related Questions