2017-03-22 11 views
-2

patientId、patientFirstName、patientLastName、patientIllness、およびnotesを含めるために、割り当ては10個の患者レコードの入力を求めます。これは、姓でabcするComparatorを持つTreeSetに格納されます。私はTreeSetに10個のエントリーを入力できますが、最後のエントリーだけがプリントアウトされます

これは私が苦しんでいたコードのセクションです:私はそれは私がいることは何か本当にわからないんだけど

import java.util.Comparator; 

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

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

そして、これは、コンパレータのコードです間違っている。私も配列に "add"を配置しようとしましたが、同じ結果が得られます - 最後の患者の情報だけが出力され、 "####"の行とともに出力されます。

+1

ループの繰り返しごとに新しいTreeSetを作成するのはなぜですか? (なぜ、forかregularなのか、なぜdo-while?) – user2357112

+0

'patientHashSet = new TreeSet <>' - ** hashSet ** = ** TreeSet **、真剣に?最初に変数名のバグを修正しました。 –

答えて

1

あなたのコードで

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

ループの上にこの行を入れて、それが反復ごとに新しいセットを作成しているので、それは、ループ内で書かれています。

修正を確認してください。

+0

私が配置したとき:patientHashSet = new TreeSet <>(新しいPatientComparator());ループの外側で、患者の姓の2つ以上のエントリを(患者のメモの入力後)尋ね、次の患者のID#に移動します。 –

+0

私はあなたの問題を解決しませんでした。 –

+0

私は動いていましたpatientHashSet =新しいTreeSet <>(新しいPatientComparator());それが最終的に働くまで周り。ありがとうございました! –

関連する問題