0

I am writing the following code for a program that returns a boolean of whether or not three consecutive numbers in an array of ints add up to 7. I am getting the following exception instead of the output that I want: "java.lang.ArrayIndexOutOfBoundsException:5". Please can someone explain how I can fix this issue?

 public static void main(String[] args) {       
    int[] numbers ={2,1,5,1,0};
    System.out.println(luckysevens(numbers));     
}

public static boolean luckysevens(int array[]) {

    boolean isLucky= false;

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

        if (array[i]+array[i+1]+array[i+2]==7){
             isLucky=true;
        }
        else { 
            i++;
        }
      }   

  return isLucky;
 }

}
WitVault
  • 23,445
  • 19
  • 103
  • 133
Jonathan Math
  • 101
  • 2
  • 7

3 Answers3

0

Because you are accessing the array elements beyond its length.

For an array of length L, you can access elements in index range of 0 to L-1.

The above exception arises when you access elements beyond this index range.

You don't even need to increment in the else condition.

 public static void main(String[] args) {       
    int[] numbers ={2,1,5,1,0};
    System.out.println(luckysevens(numbers));

}

public static boolean luckysevens(int array[]) {

    boolean isLucky= false;



    for (int i=0; i<array.length-2; i++){

        if (array[i]+array[i+1]+array[i+2]==7){
        isLucky=true;
        }
        }


return isLucky;
}

}
  • Okay, but the method is still returning false even though it should be returning true for luckysevens(numbers). Why is this happening? – Jonathan Math Nov 21 '16 at 07:29
0

You're comparing from 0 - 5 (i.e. 6 elements, but your array has only 5), so you're going out of the bounds.

All you have to do is to go from 0 - array.length-1; therefore have to change condition part i<=array.length; to like this i<(array.length-1);

    public static void main(String[] args) {
        int[] numbers ={2,1,5,1,0};
        System.out.println(luckysevens(numbers));  
    }


    public static boolean luckysevens(int array[]) {

    boolean isLucky= false;

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

        if (array[i]+array[i+1]+array[i+2]==7){
             isLucky=true;
        }
        else { 
            i++;
        }
      }   

  return isLucky;
 }
Sachith Wickramaarachchi
  • 5,546
  • 6
  • 39
  • 68
0
public static void main(String[] args) 
{       
    int[] numbers ={2,1,5,1,0};
    System.out.println(luckysevens(numbers));     
}

public static boolean luckysevens(int array[]) 
{
    boolean isLucky= false;
    //Use array.length-2 in the code
    for (int i=0; i<=array.length-2; i++)
    {
        if (array[i]+array[i+1]+array[i+2]==7)
        {
             isLucky=true;
             return isLucky;
        }
    }   
    return isLucky;
}
Venkat
  • 2,549
  • 2
  • 28
  • 61