线程“main”中的异常 java.lang.ArrayIndexOutOfBoundsException: 5

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17265537/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-01 01:30:38  来源:igfitidea点击:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5

java

提问by Derek MC

public class dereks {
public static void main (String [] args){
    int array [] = {1,2,3,5,6,7};
    int sum =0;
    for(int counter=0; counter<=array.length; counter++){
        sum+=array[counter];
    }
    System.out.println(sum);
}
}

Can anyone tell me whats wrong with this?? I can't understand why I'm getting the error message "Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5 at dereks.main(dereks.java:7)" .

谁能告诉我这有什么问题吗??我不明白为什么我会收到错误消息“线程“main”中的异常 java.lang.ArrayIndexOutOfBoundsException: 5 at dereks.main(dereks.java:7)”。

回答by Patricia Shanahan

You are getting the error because your loop limit is <=array.length. The array elements are 0 through array.length-1.

您收到错误是因为您的循环限制是<=array.length. 数组元素是 0 到array.length-1

回答by Karoly Horvath

Array indices start from 0. This means that the last element is at array.length - 1.

数组索引从0. 这意味着最后一个元素在array.length - 1

Use: counter < array.length

利用: counter < array.length

回答by Bohemian

Change your for loop terminating condition from <=to <:

改变你的for循环从中止条件<=<

for(int counter=0; counter<array.length; counter++){
    sum+=array[counter];
}

Or more simply, use foreach syntax:

或者更简单地说,使用 foreach 语法:

for(int i : array){
    sum+=i;
}

The foreach syntax is preferred when you don't actually need the index each element is at.

当您实际上不需要每个元素所在的索引时,首选 foreach 语法。