2

The given part of the code gives me an ArrayIndexOutofBoundsException, but I don't actually know how to handle it.

int count = 0;
int n = sc.nextInt();
int[] a = new int[n];
for(int i=0;i<n;i++)
{
    a[i] = sc.nextInt();
}
for(int i=1; i<n; i++)
{
    if(a[i+2]>a[i+8] && a[i+3]>a[i+8] && a[i+4]>a[i+8])
    {
        count++;
    }
}
System.out.println(count);

The array should stop working when it reaches a[n-1] but it goes beyond that in the for loop and gives me the out of bounds error.

Anil M
  • 600
  • 1
  • 10
  • 22
Merus
  • 41
  • 5
  • if array size is `10`, when `i=9`, `i+8 = 17` --> a[17] ?? What do you anticipate? – snr Oct 06 '19 at 20:02
  • You are using i+8 without knowing wether the arrays length is bigger or equal to 8. Change the second i – Patrick Oct 06 '19 at 20:02
  • OOBE is an unchecked exception. Unchecked exceptions indicate that your code is wrong. Don't handle them; fix your code. – Kevin Krumwiede Oct 06 '19 at 20:03

0 Answers0