【发布时间】:2012-03-22 06:11:10
【问题描述】:
我有一个程序,其中包含有关两所大学(文理学院和某所学校的技术学院)学生的数据。洛杉矶学院在其班级中使用 ArrayList,而科技学院在其班级中使用和数组来容纳学生。我已经在这个程序中实现了迭代器模式(使用我自己的迭代器),因此有一个迭代器接口加上一个用于 LAStudents 类的具体迭代器和一个用于 TechStudents 类的具体迭代器。我已经实现了 next() 和 hasNext() 方法。学生类还有一个接口类,称为 Student,它定义了 createIterator() 方法和 read() 方法。该程序从一个文本文件中获取有关学生的数据,如下所示:
TechStudents.txt:
Smith William CompSci Tech 90 90 340
Jones Michael CompEnr Tech 45 45 100
Carter Mary SoftEng Tech 128 124 270
Harris Harry CompSci Tech 30 30 90
Wilson Brian CompSci Tech 90 90 270
Adams Susan CompEng Tech 12 12 45
Washington George SoftEng Tech 96 96 360
Jackson Andrew SoftEng Tech 62 60 145
Madison James CompSci Tech 78 76 120
Monroe Alicia CompSci Tech 87 87 256
洛杉矶学院的学生也有类似的文件。我需要做的是打印出所有学生,包括数组中的学生和 ArrayList 中的学生,并在一个循环中完成。此外,我需要在输出中按姓氏对学生进行排序。这就是我卡住的地方。我意识到我需要一个 Comparator 或者 Comparable 类,但我不知道哪个是正确的,什么是问题的最佳解决方案。是的,这是家庭作业,但我不想偷工减料,我只是想要一些帮助,以便更好地了解如何编写解决方案。毕竟是面向对象的类。
这是保存学生数据的 StudentData 类。我添加了一个 compareTo() 方法和一个 toString() (除了我最初提供的代码)。
公开课 StudentData{
private String LastName, FirstName;
private String Major;
private String College;
private int CreditHoursAttempted;
private int CreditHoursEarned;
private int QualityPoints;
public StudentData(String ln, String fn, String mj, String col,
int cha, int che, int qp) {
LastName = ln;
FirstName = fn;
Major = mj;
College = col;
CreditHoursAttempted = cha;
CreditHoursEarned = che;
QualityPoints = qp;
}
public String GetName() {
return LastName + ", " + FirstName;
}
public String GetCollege() {
return College;
}
public String GetMajor() {
return Major;
}
public int GetCreditHoursAttempted() {
return CreditHoursAttempted;
}
public int GetCreditHoursEarned() {
return CreditHoursEarned;
}
public int GetQualityPoints() {
return QualityPoints;
}
public int GPA() {
return QualityPoints / CreditHoursAttempted;
}
public int compareTo(StudentData other){
return this.LastName.compareTo(other.LastName);
}
@Override
public String toString() {
String s = GetName() + " " + College + " " + Major + " " + GPA();
return s;
}
}
以下是我从学生类调用 read() 方法然后遍历两个数据结构并打印输出的类:
公共类 ProcessStudents {
Students la = new LAStudents();
Students tech = new TechStudents();
StudentsIterator laItr = la.createIterator();
StudentsIterator techItr = tech.createIterator();
public void readAll() throws IOException {
la.read();
tech.read();
}
public void print() {
while (laItr.hasNext() && techItr.hasNext()) {
StudentData laStudent = (StudentData) laItr.next();
StudentData techStudent = (StudentData) techItr.next();
System.out.println(techStudent);
System.out.println(laStudent);
}
}
}
我尝试使用 compareTo() 方法进行排序,但没有成功。我还尝试将两个学生列表排序为一个最终列表,然后将其打印出来,但我也无法弄清楚,在我看来,它似乎违背了使用迭代器模式的目的。
我认为以上信息和代码应该足以评估我如何解决这个问题。也欢迎对遵守 OO 原则和结构提出意见。
谢谢
【问题讨论】:
-
你是怎么解决的?如果它不是微不足道的,请添加您自己的答案
标签: java design-patterns iterator while-loop