该作业要求输入10条患者记录,包括patientId,patientFirstName,patientLastName,patientIllness和notes;这将被放入一个带有比较器的TreeSet中,该比较器将使用姓氏。
这是我正在努力解决的代码部分:
public void patientRecord() {
int i = 0;
int patientRecords = 10;
Set<Patient> patientHashSet;
System.out.println("This program will create ten patient records.");
System.out.println();
do {
getPatientId();
getPatientFirstName();
getPatientLastName();
getPatientIllness();
getNotes();
patientHashSet = new TreeSet<>(new PatientComparator());
patientHashSet.add(new Patient(patientId, patientFirstName, patientLastName, patientIllness, notes));
i++;
} while (i < patientRecords);
for (Patient record : patientHashSet) {
System.out.println(record.patientId + " " + record.patientLastName + ", " + record.patientFirstName + " "
+ record.patientIllness + " " + record.notes);
System.out.println("##########################################################################");
}
}
这是比较器代码:
import java.util.Comparator;
public class PatientComparator implements Comparator<Patient> {
@Override
public int compare(Patient o1, Patient o2) {
return o1.patientLastName.compareTo(o2.patientLastName);
}
}
我不确定我做错了什么。我也尝试将“添加”放入一个数组中,但这会产生相同的结果 - 只打印出最后一个患者的信息,以及“####”行。
答案 0 :(得分:1)
将此行放在循环上方
patientHashSet = new TreeSet<>(new PatientComparator());
在你的代码中,它被写在循环中,因此它在每次迭代时都会创建一个新的集合。
检查纠正。