【发布时间】:2018-03-11 23:59:56
【问题描述】:
我正在编写一个简单的程序,用于存储每个学生学习的课程信息并打印学生学习的每门课程。
该程序由三个类组成,其中一个类称为课程,其中存储学生所修的课程名称和学生在该课程中获得的分数。一个类的对象存储一个课程信息。
public class Course
{
// instance variables - replace the example below with your own
private String courseName;
private int testMarks;
private String result;
/**
* Constructor for objects of class Course
* The constructor stores the information of a course
*/
public Course(String name,int marks)
{
courseName=name;
testMarks=marks;
}
public String toString(String name,int marks) //combine the course name with the mark to make a string and return the string.
{
// put your code here
String score=Integer.toString(marks);
result=name+", "+score;
return result;
}
}
the another class is UniversityStudent that stores the information of each student namely the name of a student, number of course the student takes and the course list of the student.
public class UniversityStudent
{
// instance variables - replace the example below with your own
private String studentName;
private int courseNumber;
private Course[] list;
/**
* Constructor for objects of class UniversityStudent
*/
public UniversityStudent(String name,int number,Course[] a)
{
// initialise instance variables
studentName=name;
courseNumber=number;
list=a; //the course list of each student
}
public void print() //print out the course that each student takes.
{
// put your code here
System.out.println("Student Name:"+studentName);
for(int i=0;i<courseNumber;i++)
{
System.out.println(list[i].toString());
}
}
}
还有,主要方法。 main 方法创建两个对象数组。一个对象数组存储每个学生学习的课程。
public class Test1Q2A
{
public static void main(String[] args)
{
Course[] listA=new Course[10];
listA[0]=new Course("EIE3320",60);
listA[1]=new Course("EIE3105",40);
UniversityStudent studentA=new UniversityStudent("John",2,listA);
studentA.print();
Course[] listB=new Course[10];
listB[0]=new Course("COMP1001",84);
listB[1]=new Course("EIE3105",68);
listB[2]=new Course("EIE3320",52);
UniversityStudent studentB=new UniversityStudent("Mary",3,listB);
studentB.print();
}
}
我想在 Course 类中调用方法 toString() 以返回类 Course 中保存的字符串,但是当我在 University student 类中使用 print() 方法打印出字符串时,我无法获得所需的结果。有什么问题?
【问题讨论】: