2016-03-30 7 views
0

Ich versuche ein einfaches Programm zu erstellen, das die Gesamtnote von 3 Studenten berechnet, indem ich die einzelnen Markierungen durch einen Konstruktor übergebe.Warum bekomme ich ArrayIndexOutOfBounds Ausnahme?

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


    } 
} 

Antwort

4

Ihr total Array initialisiert wird, während n noch 0 ist, so ist es ein leeres Array.

hinzufügen

total = new int[x]; 

zu Ihrem Konstruktor.

0

n & Array-Gesamt Instanzvariablen nach Ihrem code.so Standardwert n = 0.then schließlich Gesamt Feldgrße worden 0.

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

innerhalb des Konstruktors im Code

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

Code sollte

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



      } 
     } 
so sein
Verwandte Themen