2014-07-17 5 views
0

여기에서 일반적인 학생은 과제의 최종 단계에 대한 정보를 얻으려고합니다. 올바른 방향으로 나를 안내하는 데 도움이나 조언을 주시면 감사하겠습니다.PriorityQueue 지원 구현

우리 임무 중 일부는 응급실 PriorityQueue를 구현하는 것입니다.

A :

함께 PatientQueue라는 클래스를 작성 : 다음과 같다에서 부품의 세부 사항은 내가 갇혔어요. 디폴트의 ​​인수 없음 생성자

b. 두 가지 공개 방법 :
i. public void registerPatient (환자 p)
ii. 공개 환자 getNextPatient()

c. Patient.java에서

: PatientComparator.java에서

package blah; 

import java.util.Date; 

public class Patient { 

// data fields 
protected String name; 
protected int category; 
protected Date timeArrived; 

// accessors and mutators 
public String getName() { 
    return name; 
} 
public void setName(String nameIn) { 
    this.name = nameIn; 
} 
public int getCategory() { 
    return category; 
} 
public void setCategory(int categoryIn) { 
    this.category = categoryIn; 
} 

public java.util.Date getTimeArrived() { 
    return timeArrived; 
} 

// default constructor 
public Patient() { 
    this.name = "Default Name"; 
    this.category = 5; // unclassified Patients go to the end of the queue 
    this.timeArrived = new Date(); 
} 

// overloaded constructor 
public Patient(String nameIn, int categoryIn) { 
    this.name = nameIn; 
    this.category = categoryIn; 
    this.timeArrived = new Date(); 
} 

} // end Patient class 

:

package blah; 

import java.util.Comparator; 

public class PatientComparator implements Comparator<Patient> { 

public int compare(Patient p1, Patient p2) { 
    if (p1.getCategory() < p2.getCategory()) 
     return -1; 
    if (p1.getCategory() > p2.getCategory()) 
     return 1; 
    else { if (p1.getTimeArrived().before(p2.getTimeArrived())) 
     return -1; 
      if (p1.getTimeArrived().after(p2.getTimeArrived())) 
     return 1; 
    } 
    return 0; 
} 

} // end PatientComparator class 

PatientQueue에서 내부 사용해, PriorityQueue의 사용과 PatientComparator 여기

내가 지금까지 가지고 무엇을 .java :

package blah; 

import java.util.Comparator; 
import java.util.PriorityQueue; 

public class PatientQueue extends PriorityQueue<Patient> { 

// default constructor 
public PatientQueue() { 

} 

public void registerPatient(Patient p) { 
      //NEED HELP IN THIS PART// 
} // end registerPatient method 

public Patient getNextPatient() { 
    return (Patient)this.poll(); 
} // end getNextPatient method 

} // end PatientQueue class 

그리고 마지막으로 EmergencyRoomSimulator.java 드라이버에서 : package blah;

import java.util.Random; 

public class EmergencyRoomSimulator { 

private static final int WAIT_LIMIT = 3000; // 1000 = 1 second 

private PatientQueue pq = new PatientQueue(); 

private void t() { 
    try { Thread.sleep(new Random().nextInt(WAIT_LIMIT)); 
    } catch (InterruptedException e) { 
    } 
} // end t method 

private void patientArrives(Patient p) { 
    pq.registerPatient(p); 
    System.out.println(" ARRIVAL: " + p.getName()); 
    System.out.println(" time arrived: " + p.getTimeArrived()); 
    System.out.println(" category: " + p.getCategory()); 
    System.out.println("------------------------------------"); 
    t(); 
} // end patientArrives method 

private void doctorVisits() { 
    Patient p = pq.getNextPatient(); 
    System.out.println(" VISIT: " + p.getName()); 
    System.out.println(" time arrived: " + p.getTimeArrived()); 
    System.out.println(" category: " + p.getCategory()); 
    System.out.println("------------------------------------"); 
    t(); 
} // end doctorVisits method 

private void simulate() { 
    System.out.println("------------------------------------"); 
    System.out.println("ER OPEN"); 
    System.out.println("------------------------------------"); 
    patientArrives(new Patient("John Paul Jones", 3)); 
    patientArrives(new Patient("Thomas Paine", 1)); 
    patientArrives(new Patient("Joseph Brant", 2)); 
    doctorVisits(); 
    patientArrives(new Patient("Ethan Allen", 2)); 
    patientArrives(new Patient("Henry Knox", 4)); 
    patientArrives(new Patient("Patrick Henry", 2)); 
    doctorVisits(); 
    doctorVisits(); 
    patientArrives(new Patient("Mary Draper", 1)); 
    patientArrives(new Patient("Samuel Adams", 3)); 
    doctorVisits(); 
    doctorVisits(); 
    doctorVisits(); 
    doctorVisits(); 
    doctorVisits(); 
    System.out.println("------------------------------------"); 
    System.out.println("ER CLOSED"); 
    System.out.println("------------------------------------"); 
} // end simulate method 

public static void main(String[] args) { 
    EmergencyRoomSimulator er = new EmergencyRoomSimulator(); 
    er.simulate(); 
} // end main 

} // end class 

내가지고있어 오류는 다음과 같습니다 주에서 처음으로 doctorVisits() 호출 스레드 "주요"java.lang.NullPointerException이

에서

예외입니다. 실제로 추가하거나 목록에서 객체를 제거하는 적절한 방법이 없다는 것을 알고 있지만 PatientQueue 클래스에서 실제로 발생해야하는 것을 볼 수 없으며 실제로는 PriorityQueue이 추가되거나 "get "다음 환자.

다시, 모든 조언을 크게 주시면 감사하겠습니다. 감사!

+1

로 필드 선언을 변경을 왜 사용'당신의 registerPatient에 (P)'pq.add 방법? – Reins

+0

"pq"는 내가 그 라인을 추가했다면 그 메소드에서 인식 (해결)되지 않을 것이다. 나는 이론에있어서 그것이 필요한 것에 더 가깝다는 것에 동의하지만, 여전히 pq (메인에서)와 관련이있다. to registerPatient. –

답변

1

별도의 Comparator를 만들지 않습니다. Patient 클래스에 Comparable 인터페이스를 구현하고 필요한 compareTo 메소드를 구현할 수 있습니다. 빠른 구현 :

@Override 
public int compareTo(Object o) { 
    Patient p = (Patient) o; 
    if (this.getCategory() < p.getCategory()) 
     return -1; 
    if (this.getCategory() > p.getCategory()) 
     return 1; 
    else { if (this.getTimeArrived().before(p.getTimeArrived())) 
     return -1; 
     if (this.getTimeArrived().after(p.getTimeArrived())) 
      return 1; 
    } 
    return 0; 
} 

은 또한 당신의 registerPatient 방법에 this.add(p)를 추가합니다.

프로그램을 작동시키는 데 필요한 다른 방법은 없습니다. Comparable 인터페이스에 대한 자세한 정보 : 좀 더 신중하게 할당을 보았고, 실제로는 말한다 http://docs.oracle.com/javase/7/docs/api/java/lang/Comparable.html


편집 //

귀하의 코멘트 후 :

다. PriorityQueue 및 PatientComparator의 내부 사용

이것은 실제로 PriorityQueue를 확장 할 필요가 없지만 내부 리소스로 사용할 수 있다는 것을 의미합니다. 여기가 PatientQueue 클래스를 구현하는 것이 방법입니다

import java.util.Comparator; 
import java.util.PriorityQueue; 

public class PatientQueue { 
    PriorityQueue pq; 

    // default constructor 
    public PatientQueue() { 
     this.pq = new PriorityQueue<Patient>(1, new PatientComparator()); 
    } 

    public void registerPatient(Patient p) { 
     this.pq.add(p); 
    } // end registerPatient method 

    public Patient getNextPatient() { 
     return (Patient) this.pq.poll(); 
    } // end getNextPatient method 

} // end PatientQueue class 

하고 EmergencyRoomSimulator 클래스

그냥

PatientQueue pq = new PatientQueue();

+0

감사합니다. - 생성되는 4 개의 클래스가 과제에 지정되어 있으므로 사용하는 클래스와 계층에 관해 손이 막혔습니다. 그러나 분명히 답장을 고맙게 생각합니다. –

+0

@ SO-Darkater 나는 대답을 편집했다. 아마도 도움이 될 수있다. – Reins

+0

과제의 다른 요구 사항을 제외하고는 완벽하게 작동합니다. "두 명의 환자를 비교하기 위해 Comparator 인터페이스를 구현하는 PatientComparator라는 클래스 작성 a) 하위 카테 고 리가있는 환자를 우선 확인해야합니다 .b) 2 명의 환자 간의 카테고리가 동일하면 , 이전에 도착한 환자가 먼저보아야합니다 "- 따라서, 나는 그 별도의 수업을 사용해야합니다. –

1

PatientQueuePatientComparator을 사용하지 않습니다. 수퍼 클래스의 생성자를 사용하여 등록해야합니다.

그리고 PatientQueuePatient 개체를 대기열에 추가하지 않습니다. registerPatient 방법으로 추가하십시오.

+0

답장을 보내 주셔서 감사합니다! 첫 번째 코멘트에서는 우선 순위 큐의 새 인스턴스를 만들기 위해 수퍼 클래스 (PriorityQueue)의 생성자를 사용해야한다고 말하고 있습니까? 이와 유사합니다 : "PatientComparator pc;" 데이터 필드로? –

+0

그리고 두 번째 성명에 관해서 : 그것은 내가 갇혀있는 곳입니다. 대기열 자체는 main 메소드에서 생성되며, "pq"(main에서 생성 된 객체)를 참조하면 해결되지 않습니다. "this.add (p); 사용" NullPointerException을 발생시킵니다. –

+0

우선, PriorityQueue에 비교자를 부여하는 방법을 찾아야한다는 것을 의미합니다. PatientQueue는 PriorityQueue를 확장하므로 슈퍼 생성자를 사용해야합니다. –