-2

The assignment asks for entry of 10 patient records, to include patientId, patientFirstName, patientLastName, patientIllness, and notes; this is to be put into a TreeSet with a Comparator that will abc by last name.

This is the section of code that I am struggling with:

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("##########################################################################");
    }
}

And this is the Comparator code:

import java.util.Comparator;

public class PatientComparator implements Comparator<Patient> {
    @Override
    public int compare(Patient o1, Patient o2) {
        return o1.patientLastName.compareTo(o2.patientLastName);
    }
}

I'm not really sure what it is that I'm doing wrong. I have also tried placing the "add" into an array, but that produces the same results--only the last patient's information prints out, along with the line of "####".

user123
  • 8,970
  • 2
  • 31
  • 52
J.Speer
  • 1
  • 3
  • 1
    Why are you making a new TreeSet on every iteration of the loop? (And why a do-while, rather than a for or a regular while?) – user2357112 Mar 22 '17 at 04:50
  • `patientHashSet = new TreeSet<>` -- **hashSet** = **TreeSet**, seriously? Lets fixed the bugs in your variable names first. – Erwin Bolwidt Mar 22 '17 at 04:53

1 Answers1

1

Put this line above the loop

patientHashSet = new TreeSet<>(new PatientComparator());

In your code, it is written inside the loop, so it is creating a new set on every iteration.

Check the correction.

Pang
  • 9,564
  • 146
  • 81
  • 122
abhishek sahu
  • 648
  • 4
  • 8
  • When I had placed: patientHashSet = new TreeSet<>(new PatientComparator()); outside the loop, it then asked for two more entries of the patient's last name (after the entry of patient notes), before moving onto the next patient's id#. – J.Speer Mar 22 '17 at 06:16
  • i didnt get your problem. – abhishek sahu Mar 22 '17 at 12:01
  • I kept moving patientHashSet = new TreeSet<>(new PatientComparator()); around until it finally worked. Thank you! – J.Speer Mar 23 '17 at 13:18