【问题标题】:Why I am getting ArrayIndexOutOfBounds exception?为什么我收到 ArrayIndexOutOfBounds 异常?
【发布时间】:2016-03-30 11:44:23
【问题描述】:

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


  }
} 

【问题讨论】:

    标签: java java-7


    【解决方案1】:

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

    添加

    total = new int[x];
    

    给你的构造函数。

    【讨论】:

      【解决方案2】:

      n & total array 是 instance variables 根据您的代码。所以默认值 n=0.then 总数组大小最终变为 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);
      
      
      
                  }
              }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-11-08
        • 2013-02-10
        • 2014-07-01
        • 1970-01-01
        • 1970-01-01
        • 2015-01-28
        • 2010-10-15
        • 1970-01-01
        相关资源
        最近更新 更多