为什么我会收到 ArrayIndexOutOfBounds 异常?

Why I am getting ArrayIndexOutOfBounds exception?

我正在尝试制作一个简单的程序,该程序通过将个人分数传递给构造函数来计算 3 名学生的总分。

class Student{
int n;
int[] total = new int[n];

Student(int x, int[] p, int[] c, int[] m){

    int n = x;
    for(int i = 0; i < n; i++){

        total[i] = (p[i] + c[i] + m[i]);

        System.out.println(total[i]);
    }

  }
}

class Mlist{

public static void main(String args[]){

    String[] name = {"foo", "bar", "baz"};
    int[] phy = {80,112,100};
    int[] chem = {100,120,88};
    int[] maths = {40, 68,60};

    Student stud = new Student(name.length, phy, chem, maths);


  }
} 

您的 total 数组已初始化,而 n 仍为 0,因此它是一个空数组。

添加

total = new int[x];

给你的构造函数。

n & total array 是 instance variables 根据你的 code.so 默认值 n=0.then 最后 total array size 变成 0.

int[] total = new int[0];    //empty array

您代码中的构造函数内部

`int n = x;` //this not apply to total array size.so it is still an empty array.

代码应该是这样的

class student{

      student(int x, int[] p, int[] c, int[] m){

                int[] total = new int[x];

                for(int i = 0; i < x; i++){

                    total[i] = (p[i] + c[i] + m[i]);

                    System.out.println(total[i]);
                }

            }
        }

        class Mlist{

            public static void main(String args[]){

                String[] name = {"foo", "bar", "baz"};
                int[] phy = {80,112,100};
                int[] chem = {100,120,88};
                int[] maths = {40, 68,60};
                System.out.println(name.length);
                student stud = new student(name.length, phy, chem, maths);



            }
        }