-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
  • 34,719
  • 24
  • 185
  • 251

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,333
  • 29
  • 50
  • Wow,, that one mistake was haunting me for like 2 weeks before I asked for help. Thank you very much, I can continue now my work. –  Feb 01 '15 at 09:54
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
  • 374,785
  • 51
  • 663
  • 734