2017-01-26 63 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>