错误消息:线程“main”中的异常java.lang.ArrayIndexOutOfBoundsException

时间:2015-02-01 09:48:05

标签: java for-loop indexoutofboundsexception

我收到错误消息:

  

线程中的异常" main" java.lang.ArrayIndexOutOfBoundsException

使用此代码:

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;
        }
    }
}

2 个答案:

答案 0 :(得分:3)

你应该使用&lt;而不是&lt; =

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

如果你有一个由一个元素组成的数组,它的长度将为1,但它的唯一元素的索引将为0 如果您尝试访问索引为1的元素(即array.length),您将获得一个ArrayIndexOutOfBoundsException

答案 1 :(得分:1)

更改

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

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

数组索引从0开始,以长度-1结束。