2016-03-30 18 views
0

私は、個々のマークをコンストラクタに渡して3人の学生の合計マークを計算する簡単なプログラムを作ろうとしています。 nはまだ0である間なぜArrayIndexOutOfBounds例外が発生していますか?

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); 


    } 
} 

答えて

4

あなたtotal配列が初期化されるので、それは空の配列です。

は、あなたのコンストラクタに

total = new int[x]; 

を追加します。コード内

コンストラクタの内部
0
N &総アレイは インスタンス変数あなたcode.soデフォルト値N = 0.then最終的に総アレイサイズに従ってなっさ
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); 



      } 
     } 
関連する問題