为什么我得到ArrayIndexOutOfBounds异常?

时间:2016-03-30 11:44:23

标签: java java-7

我正在尝试制作一个简单的程序,通过在构造函数中传递单个标记来计算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);


  }
} 

2 个答案:

答案 0 :(得分:4)

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

添加

total = new int[x];

到你的构造函数。

答案 1 :(得分:0)

n&amp;根据你的代码,总数组是实例变量。所以默认值n = 0.然后最终总数组大小变为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);



            }
        }