我有一个名为Student的构造函数:
public Student(String suppliedFirstName, String suppliedLastName, int suppliedAge) {
firstName = suppliedFirstName;
lastName = suppliedLastName;
age = suppliedAge;
}
一个名为Section:
的构造函数public Section(String inName, int inMaximum) {
name = inName;
maximumStudents = inMaximum;
List<Student> studentRoster = new ArrayList<Student>();
List<Student> studentWaitList = new ArrayList<Student>();
}
我想通过调用学生构造函数将学生添加到studentRoster列表中的方法:
public void signUp(Student inStudent()) {
if(studentRoster.size() == maximumStudents) {
studentWaitList.add(inStudent());
return;
}
studentRoster.add(inStudent());
}
在尝试执行此操作时,我仍然遇到错误,说我还没有完成MethodDeclaration。正确执行此操作的正确语法是什么?
答案 0 :(得分:0)
试试这个:
public void signUp(Student inStudent) {
if (studentRoster.size() == maximumStudents) {
studentWaitList.add(inStudent);
return;
}
studentRoster.add(inStudent);
}
答案 1 :(得分:0)
如果您想将Student
实例传递给signUp()
方法,则应该是:
public void signUp(Student inStudent) {
if(studentRoster.size() == maximumStudents) {
studentWaitList.add(inStudent);
return;
}
studentRoster.add(inStudent);
}
然后你必须调用如下方法:
signUp(new Student(...));
或
Student lastStudent = new Student(...);
signUp(lastStudent);
注意这样做,Student
实例正在初始化,然后才传递给方法signUp
。换句话说,构造函数在传递给方法之前就被调用了。
此外,您必须将studentRoster
和studentWaitList
声明为类Section
的字段。在
public Section(String inName, int inMaximum) {
name = inName;
maximumStudents = inMaximum;
List<Student> studentRoster = new ArrayList<Student>();
List<Student> studentWaitList = new ArrayList<Student>();
}
它们被声明为局部变量。你可能想要这样做:
public class Section {
List<Student> studentRoste;
List<Student> studentWaitList;
public Section(String inName, int inMaximum) {
name = inName;
maximumStudents = inMaximum;
studentRoster = new ArrayList<Student>(); // INITIALIZE
studentWaitList = new ArrayList<Student>();
}
}