Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/385.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 在通过方法传递的数组中添加值?_Java - Fatal编程技术网

Java 在通过方法传递的数组中添加值?

Java 在通过方法传递的数组中添加值?,java,Java,出于某种原因,我得到了一个错误的代码说: private void setAverage(int[] grades1) { for(int i = 0; i <= grades1.length; i++){ avg += grades1[i]; } System.out.println(avg); } 你必须使用 例如,你有一个长度为3的数组,然后你有索引0,1,2。 您不能尝试获取索引3您正在获取ArrayIndexOutOfBou

出于某种原因,我得到了一个错误的代码说:

private void setAverage(int[] grades1) {

    for(int i = 0; i <= grades1.length; i++){
        avg += grades1[i];
    }

    System.out.println(avg);     
}
你必须使用 例如,你有一个长度为3的数组,然后你有索引0,1,2。 您不能尝试获取索引3

您正在获取ArrayIndexOutOfBoundsException:3,因为您的代码试图访问数组中不存在的grades1[3]元素。让我们仔细看看:

数组的长度为3。这意味着您的数组从索引0开始,到索引2结束---->[0,2]。如果你数一数数字0,1,2,你会得到3,也就是长度


现在,for循环中的逻辑已关闭。您从i=0开始,到我阅读了此例外情况的文档结束。终止声明应使用小于、不小于或等于。为什么对该问题投反对票?
   Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
   at StudentRecords.setAverage(StudentRecords.java:29)
   at StudentRecords.<init>(StudentRecords.java:16)
   at StudentRecordTest.main(StudentRecordTest.java:54)
private void setAverage(int[] grades1) {
    for(int i = 0; i < grades1.length; i++){
        avg += grades1[i];
    }
    System.out.println(avg);     
}
private void setAverage(int[] grades1) {

for(int i = 0; i < grades1.length; i++){
    avg += grades1[i];
}

System.out.println(avg);     
}
// iteration 1
for(int i = 0; i <= grades1.length; i++){
        avg += grades1[i];// accesses grades1[0]
    }
-------------------------------------------------
// iteration 2
for(int i = 0; i <= grades1.length; i++){
        avg += grades1[i];// accesses grades1[1]
    }
-------------------------------------------------
// iteration 3
for(int i = 0; i <= grades1.length; i++){
        avg += grades1[i];// accesses grades1[2]
    }
-------------------------------------------------
// iteration 4
for(int i = 0; i <= grades1.length; i++){
        avg += grades1[i];// tries to access grades1[3] which does not exist
    }
-------------------------------------------------
1. for (int i = 0; i < grades1.length; i++)

2. for (int i = 0; i <= grades1.length - 1; i++)