-4

I got error message:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException

With this code:

public class probno {

    public static void main(String arghs[]) {

        int niz[]={3,2,5,6,8};
        promjena(niz);

        for(int y:niz){
            System.out.println(y);
        }
    }   

    public static void promjena (int x[]){

        for (int brojac=0;brojac<=x.length;brojac++){
            x[brojac]+=5;
        }
    }
}
Cœur
  • 37,241
  • 25
  • 195
  • 267

2 Answers2

4

You should use < instead of <=

for (int brojac=0;brojac<=x.length;brojac++){
    x[brojac]+=5;
}

If you have array which consists say of one element, its length will be 1, but the index of it's only element will be 0 If you try to access an element with index 1 (i.e. array.length) you will get an ArrayIndexOutOfBoundsException

bedrin
  • 4,458
  • 32
  • 53
1

Change

for (int brojac=0;brojac<=x.length;brojac++)

to

for (int brojac=0;brojac<x.length;brojac++)

Array indices start in 0 and end in length-1.

Eran
  • 387,369
  • 54
  • 702
  • 768