-1

when i code this no error appears to me but when compile it >> give me error >> what is the wrong with that ??

public static void main (String args []){
    int arr[] = {20 , 30 ,40 , 50 , 60 ,200 };

    int searchKey = 20 ; 


    for (int i = 0 ; i < arr.length ; i++ ){

        if (arr[i]== searchKey){
            System.out.println(searchKey + "found");
            for(int z = i ; z < arr.length ;z++){
                arr[z] = arr[z+1];
            }
            for(int k=0 ; k<arr.length ; k++)
                System.out.print(arr[k] + " ");

            break;
        }
        else if (i ==  (arr.length-1) ) {
             System.out.print(searchKey+  " not found");
             break;
        }
    }

}
Scary Wombat
  • 44,617
  • 6
  • 35
  • 64

2 Answers2

0

With this for loop you go in java.lang.ArrayIndexOutOfBoundsException. Replace

for(int z = i ; z < arr.length ;z++)

With arr.length-1 instead arr.length:

for(int z = i ; z < arr.length-1 ;z++)
Abdelhak
  • 8,299
  • 4
  • 22
  • 36
0

I can see that you would get an out of bounds exception with

for(int z = i ; z < arr.length ;z++) {
    arr[z] = arr[z+1];
}

try reducing the looping by

for(int z = i ; z < arr.length -1 ;z++)
Maroun
  • 94,125
  • 30
  • 188
  • 241
Scary Wombat
  • 44,617
  • 6
  • 35
  • 64