Harshit Jain Harshit Jain - 6 months ago 10
Java Question

Array Index out of bounds Exception on second test case

import java.util.Scanner;
class Little_elephant
{
public static void main(String args[])
{
Scanner scan = new Scanner(System.in);
int t = scan.nextInt();
int arr[] = new int[100];
int inversions, localInversions;
for(int i = 0; i < t; i++)
{
inversions = 0;
localInversions = 0;
int n = scan.nextInt();
for(int j = 0; j < n; j++)
{
arr[j] = scan.nextInt();
}
for(int j = 0; j < n - 1; j++)
{
for(int k = j + 1; j < n; k++)
{
if(arr[j] > arr[k])
{
inversions++;
}
}
if(arr[j] > arr[j+1])
localInversions++;
}
if(inversions == localInversions)
System.out.println("YES");
else
System.out.println("No");
}
}
}
}


The program is showing no error on compilation but is getting an array index out of bounds exception at 23rd line. Also the error is when I try more than one case i.e t>1. Please someone help me!

Answer

You have a loop for(int k = j + 1; j < n; k++)
You're increasing k but the condition is on j