Home > OS >  is there any better way to handel IndexOutOfBoundsException?
is there any better way to handel IndexOutOfBoundsException?

Time:01-31

int sum(int[] arr,int size,int suma){
  if(size < 0) return suma; 

   return   sum(arr,size-1, suma arr[size]);
}

This code works fine as it breaks when the size is less than zero, but also give java.lang.IndexOutOfBoundsException : Invalid array index: -1 while debugging. what else I can do to avoid this IndexOutOfBoundsException?

CodePudding user response:

The minimum array's index is 0, so you should at last add arr[length - 1] to the final sum. Therefore you should stop the recursion if the length is 0;

public static int sum(int[] arr, int length, int sum) {
    return length == 0 ? sum : sum(arr, length - 1, sum   arr[length - 1]);
}

Demo:

int[] arr = { 1, 2, 3, 4, 5, 6 };
System.out.println(sum(arr, arr.length, 1000)); // 1021

CodePudding user response:

How about:

int sum(int[] arr,int size,int suma){
   if (size < 1) return suma; 

   return   sum(arr,size-1, suma arr[size-1]);
}

The index should never be equal to the size anyway since indexes start from 0.

  •  Tags:  
  • Related