Reputation: 1141
I am new in java and witing a programm to delete an element with specific position. I know there are many possible answer but i am trying here my own. I am getting the error :
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 9
at
Array.DeleteElement.delete(DeleteElement.java:24)
at
Array.DeleteElement.main(DeleteElement.java:14)
Now Here I am passing array and position. Where it is getting incorrect index. As per documentaion it is saying array has been accessed with an illegal index. Can anybody please explain me how it is illegal and where I am getting wrong.
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
//int[] delArray = new int[15];
int[] delArray = {20,50,60,9,8,7,1,5,3};
System.out.println("Enter Element you want to delete");
int del = in.nextInt();
int pos = InsertSearch.searchKey(delArray,del);
System.out.println(pos);
if(pos != -1){
delete(delArray,del,pos);
for(int i=0; i<delArray.length; i++)
System.out.println(delArray[i]);
}
else
System.out.println(del+"Not exist in array");
}
public static int delete(int delArr[], int del, int pos){
for(int i=pos; i<delArr.length; i++)
delArr[i] = delArr[i+1];
return delArr.length -1;
}
Upvotes: 1
Views: 2072
Reputation: 3323
This snippet of code is problem
for(int i=pos; i<delArr.length; i++)
delArr[i] = delArr[i+1];
Precisely, delArr[i] = delArr[i+1]
. The issue is i+1
.
In Java indices in an array starts with 0, and the last index is N-1 for the array which has length N.
You loop should be for(int i=pos; i<delArr.length-1; i++)
.
Upvotes: 1
Reputation: 15852
Look,
public static int delete(int delArr[], int del, int pos){
for(int i=pos; i<delArr.length; i++)
delArr[i] = delArr[i+1]; //<---- HERE
return delArr.length -1;
}
in this loop, i
goes up to the max index of the array, but inside, you access i+1
th element which in this case causes IndexOutOfBoundsException
being thrown.
From the stacktrace, you can read, that you tried to access 9th element but your array has only indexes from 0 to 8 incl.
Upvotes: 1
Reputation: 5695
Here
delArr[i] = delArr[i+1];
When i
is equal to 8
, then i+1
gives 9
, which generates the Exception
Upvotes: 1