有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

private void setAverage(int[] grades1) {

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

    System.out.println(avg);     
}

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

   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)

共 (3) 个答案

  1. # 1 楼答案

    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

  2. # 2 楼答案

    因为代码试图访问数组中不存在的grades1[3]元素,所以得到了ArrayIndexOutOfBoundsException: 3。让我们仔细看看:

    数组的长度为3。这意味着您的数组从index 0开始,到index 2->[0, 2]。如果你数数0, 1, 2,,你会得到3,这是长度

    现在,逻辑在for循环中关闭。你从i = 0开始,到i <= 3结束。在for循环中访问grades1[i]时,访问每个元素i,直到条件为false

    // 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++)
    

    希望这有帮助:-)

  3. # 3 楼答案

    你必须使用<而不是<=。在您的代码中,如果grades1的大小为10,您将尝试在循环结束时获取grades1[10],而只能从0到9

    private void setAverage(int[] grades1) {
        for(int i = 0; i < grades1.length; i++){
            avg += grades1[i];
        }
        System.out.println(avg);     
    }