-1

Can anyone try to solve this as I am getting

ArrayIndexOutOfBoundsException

when tried to subtract last element from 3 if the result is not present then it should return next element of the result.

public static int[] returnNum(){
    int[] numbers = {1,2,4,6,8,10};
    int[] num = {};
    for(int i = numbers.length-1; i > 0; i--){
        if(numbers[i]-3 == numbers[i-1]){
            num[numbers.length-1-i] = numbers[i-1];
        }else{
            num[numbers.length-1-i] = numbers[i-1];
        }
    }
    return num;
}
public static void main(String[] args) {        
    System.out.println(Test.returnNum());
}
depperm
  • 10,606
  • 4
  • 43
  • 67
Bhanu Prakash
  • 41
  • 1
  • 9

2 Answers2

3

Your array "num" is initialized to an empty array ( "{}" ) which has size 0.

Trying to access it in the else branch of your if at any position will throw IndexOutOfBound.

else{
        num[numbers.length-1-i] = numbers[i-1];
    }

(NOTE: this is also true for the main branch of your if, it's just that that's never reached given your statically initialized example).

Once you initialize an array, you can't dynamically add stuff to it. If that's your use case, you should look into the List data structure

Diego Martinoia
  • 4,592
  • 1
  • 17
  • 36
0

num has a length of 0. Initialize it instead by using int[] num = new int[numbers.length -1];

cbender
  • 2,231
  • 1
  • 14
  • 18