我正在编写一个简单的程序,用于存储每个学生参加的类(class)信息并打印学生参加的每门类(class)。
该程序由三个类组成,其中一个类称为“类(class)”,它存储学生所修读的类(class)名称以及学生在该类(class)中获得的分数。类(class)的一个对象存储一份类(class)信息。
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方法创建两个对象数组。一个对象数组存储每个学生所修读的类(class)。
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()打印字符串时,我无法得到所需的结果。有什么问题吗?
最佳答案
这是因为您实际上并未重写 toString()
方法。您的方法有一组参数,因此是一种完全不同的方法。因此,您要么需要在调用 Course.toString(String name,intmarks)
方法的位置添加参数,要么需要将 toString
方法更改为不带参数的方法。我建议这样做:
public String toString() {
String score = Integer.toString(testMarks);
result = courseName + ", " + score;
return result;
}
关于java - 在对象数组的元素中调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46499684/