在测试程序类中打印一个数组



我正试图返回Course类的测试类中的学生数组,但我一直收到.class预期的错误。我试过了students[].TestCourse,但这也不起作用。

public class Course {
private String courseName;
private String[] students = new String[4];
private int numberOfStudents;

public Course(String courseName) {
this.courseName = courseName;
}

public void addStudent(String student) {
if (numberOfStudents == students.length) {
String [] copy = new String [students.length*2];
System.arraycopy(students,0,copy,0,students.length);
students = copy;
}

students[numberOfStudents] = student;
numberOfStudents++;
}

public String[] getStudents() {
return students;
}

public void dropStudent(String student) {
for (int i=0;i<students.length;i++) {
if (students[i]==student) {
students[i] = null;
}
for (i=i;i<students.length-1;i++) {
students[i] = students[i+1];
}
}
}
}
public class TestCourse {
public static void main() {
Course compScience = new Course("Computer Science");
compScience.addStudent("Jack");
compScience.addStudent("Dean");
compScience.addStudent("Leon");
compScience.dropStudent("Dean");
System.out.println("The students currently in this course are "+ students[]);
}
}

main方法中的行更改为:

System.out.println("The students currently in this course are "+ Arrays.toString(compScience.getStudents()));

它应该会着火!

您所做的只是尝试在需要通过创建Course compScience = new Course("Computer Science");的引用访问类的字段时直接调用它。。。则按如下CCD_ 5调用它的方法CCD_。要获得数组的内容,您需要如上所述在Arrays.toString()中包装此方法调用。

最新更新