Search code examples
algorithmcomputer-science

How to fix this java.lang.ArrayIndexOutOfBoundsException error for this code?


public class Problem1 {

public static int findmaxdiff (int[] A)
{
    int max_diff = 0;

    if(A.length>=2)
    {
        max_diff = A[1] - A[0];
        int i, j;
        for (i = 0; i < A.length; i++)
        {
            for (j = i + 1; j < A.length; j++);
            {
                if (A[j] - A[i] > max_diff) {
                    max_diff = A[j] - A[i];
                }
            }
        }
    }
    return max_diff;

}



public static void main(String[] args) {
    // TODO Auto-generated method stub

    // Test your findmaxdiff() method here
    
    int[] testarray1 = {2, 3, 10, 6, 4, 8, 1};
    // maxdiff: 8
    
    int[] testarray2 = {7, 9, 1, 6, 3, 2};
    // maxdiff: 5
    
    System.out.println(findmaxdiff(testarray1));
    // Add test statements 
    
    
    
}

}

Console: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 7 out of bounds for length 7 at lab7.Problem1.findmaxdiff(Problem1.java:23) at lab7.Problem1.main(Problem1.java:46)


Solution

  • You have a semicolon at the end of your inner for loop:

    for (j = i + 1; j < A.length; j++);
    

    This is interpreted to be a single, empty statement for the body of the for loop. It's as though you had typed this:

    for (j = i + 1; j < A.length; j++) {
       ;
    }
    

    The block that follows is not part of the for loop, so it runs every time, even if j >= A.length. Removing the semicolon should do the trick.