1

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;
}
shanky singh
  • 1,121
  • 2
  • 12
  • 24

3 Answers3

1

Here

delArr[i] = delArr[i+1];

When i is equal to 8, then i+1 gives 9, which generates the Exception

dumbPotato21
  • 5,669
  • 5
  • 21
  • 34
1

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+1th 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.

xenteros
  • 15,586
  • 12
  • 56
  • 91
1

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++).

djm.im
  • 3,295
  • 4
  • 30
  • 45