2017-01-26 64 views
-4

可有人向我解釋什麼是這一類情況發生,因爲我無法理解的課程字符串數組的初始化和檔次Java類的面向對象編程

public class stud{ 
    int id; 
    String nam; 
    String courses[]; 
    double grades[]; 
    int maxSize, size; 

    public stud(int d, String n, int ms) 
    { 
    id = d; 
    nam = n; 
    courses = new String[ms]; 
    grades = new double[ms]; 
    size=0; 
    } 
    public void addCourse(String nc, double g) 
    { 
    courses[size]=nc; 
    grades[size]=g; 
    size++; 
    } 
    public void print() 
    { 
    System.out.println(id+ " "+nam); 
    for(int i=0; i<size; i++) 
     System.out.println(courses[i]+ " "+grades[i]); 
    } 
} 
+0

行'課程=新的String [毫秒]'的'陣列courses'可存儲'ms'分配內存沒有。值。 –

+0

呃,不是語法或語義意義上的理解? – DuKes0mE

+0

聽起來像你真的需要閱讀文檔或看一些教程。從字面上看,只是谷歌「java數組教程」。 -1顯然缺乏研究工作。 – tnw

回答

0

新增以下幾點意見。

public class stud { 
    int id; 
    String nam; 
    String courses[]; 
    double grades[]; 
    int maxSize, size; 

    public stud(int d, String n, int ms) 
    { 
     // initialise the attributes 
     id = d; 
     nam = n; 

     // create empty arrays with a size of ms 
     courses = new String[ms]; 
     grades = new double[ms]; 

     //point to the first item in the array 
     //Also gives the number of values in the array 
     size=0; 
    } 

    public void addCourse(String nc, double g) 
    { 
     //Add a course name and grade into the array 
     //they are added at the location pointed to by 'size' 
     courses[size]=nc; 
     grades[size]=g; 

     //Increment the pointer to the next empty array location 
     size++; 
    } 

    public void print() 
    { 
     System.out.println(id+ " "+nam); 

     //Iterate over the arrays until we get to the size 
     for(int i=0; i<size; i++) 
      System.out.println(courses[i]+ " "+grades[i]); 
    } 
} 

請注意,就其本身而言,它不會輸出任何內容。需要調用addCourse方法來添加課程。

這也是相當嚴重的編碼,你可能想看看在

Map<String, Double>