This is my linear search code but I am getting an error with the array. I know what the error is and I have fixed it, but it still shows the same error:
Runtime Error: Runtime ErrorException in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5 at LinearSearchExample.linearSearch(LinearSearchExample.java:13) at LinearSearchExample.main(LinearSearchExample.java:40)
public class LinearSearchExample
{
public static int linearSearch(int[] arr, int key)
{
for(int i=1;i<=arr.length;i++)
{
if(arr[i] == key)
{
return i;
}
}
return -1;
}
public static void main(String a[])
{
int i, n, key, arr[],testcase;
Scanner in = new Scanner(System.in);
testcase = in.nextInt();
System.out.println(testcase);
for(i=0;i<testcase;i++)
{
n = in.nextInt();
arr = new int[n];
for(i=0;i<n;i++){
arr[i] = in.nextInt();
}
key = in.nextInt();
System.out.println(linearSearch(arr, key));
}
}
}