到达时间无法在Java中正确排序

时间:2014-11-14 14:02:14

标签: java sorting linked-list

向大家致意。我目前正在制定一个程序,对紧急病人数量进行分类(护士在进入急诊室时分配的数量,这个数字也决定了他们患病的严重程度)。但是,如果有超过1名患者持有相同的紧急号码(例如:2名患者持有紧急号码1),那么较早出现的患者应首先接受治疗。出于这个原因,我有2个排序,一个是按升序对紧急号码进行排序,另一个是按升序对时间进行排序。但不幸的是,第二次排序无法正常工作。以下是紧急号码类型的解释:

紧急电话号码:1 - 立即危及生命 紧急号码:2 - 紧急,但不会立即危及生命 紧急电话号码:3 - 不太紧急

所以,现在是编码部分(请注意这是一个链表)

接口:

public interface ListInterface<T> {

  public boolean add(T newEntry);

  public boolean add(int newPosition, T newEntry);

  public T remove(int givenPosition);

  public void clear();

  public boolean replace(int givenPosition, T newEntry);

  public T getEntry(int givenPosition);

  public boolean contains(T anEntry);

  public int getLength();

  public boolean isEmpty();

  public boolean isFull();
} 

LList课程:

/**
 * LList.java
 * A class that implements the ADT list by using a chain of nodes,
 * with the node implemented as an inner class.
 */
public class LList<T> implements ListInterface<T> {
    private Node firstNode; // reference to first node
    private int  length;    // number of entries in list

    public LList() {
        clear();
    } 

    public final void clear() {
        firstNode = null;
        length = 0;
    } 

    public boolean add(T newEntry) {
        Node newNode = new Node(newEntry);  // create the new node

        if (isEmpty())                              // if empty list
            firstNode = newNode;
        else {                        // add to end of nonempty list
            Node currentNode = firstNode;                   // traverse linked list with p pointing to the current node
            while (currentNode.next != null) {      // while have not reached the last node
                currentNode = currentNode.next;
            }
            currentNode.next = newNode; // make last node reference new node
        } 

        length++;
        return true;
    }  

  public boolean add(int newPosition, T newEntry) { // OutOfMemoryError possible
        boolean isSuccessful = true;

        if ((newPosition >= 1) && (newPosition <= length+1)) {
            Node newNode = new Node(newEntry);

            if (isEmpty() || (newPosition == 1))    {     // case 1: add to beginning of list
                newNode.next = firstNode;
                firstNode = newNode;
            }
            else {                                                    // case 2: list is not empty and newPosition > 1
                Node nodeBefore = firstNode;
                for (int i = 1; i < newPosition - 1; ++i) {
                    nodeBefore = nodeBefore.next;       // advance nodeBefore to its next node
                }

                newNode.next = nodeBefore.next; // make new node point to current node at newPosition
                nodeBefore.next = newNode;      // make the node before point to the new node
            } 

            length++;
        }
        else
            isSuccessful = false;

        return isSuccessful;
    } 

    public T remove(int givenPosition) {
      T result = null;                 // return value

      if ((givenPosition >= 1) && (givenPosition <= length)) {
        if (givenPosition == 1) {      // case 1: remove first entry
          result = firstNode.data;     // save entry to be removed
          firstNode = firstNode.next;
        }
        else {                         // case 2: givenPosition > 1
            Node nodeBefore = firstNode;
                for (int i = 1; i < givenPosition - 1; ++i) {
                    nodeBefore = nodeBefore.next;       // advance nodeBefore to its next node
                }
                result = nodeBefore.next.data;  // save entry to be removed
                nodeBefore.next = nodeBefore.next.next; // make node before point to node after the
        }                                                               // one to be deleted (to disconnect node from chain)

        length--;
      } 

      return result;                   // return removed entry, or
                                       // null if operation fails
    } 

    public boolean replace(int givenPosition, T newEntry) {
        boolean isSuccessful = true;

    if ((givenPosition >= 1) && (givenPosition <= length)) {
        Node currentNode = firstNode;
            for (int i = 0; i < givenPosition - 1; ++i) {
                // System.out.println("Trace| currentNode.data = " + currentNode.data + "\t, i = " + i);
                currentNode = currentNode.next;     // advance currentNode to next node
            }
            currentNode.data = newEntry;    // currentNode is pointing to the node at givenPosition
    }
        else
            isSuccessful = false;

        return isSuccessful;
  } 

  public T getEntry(int givenPosition) {
    T result = null;  

        if ((givenPosition >= 1) && (givenPosition <= length)) {
            Node currentNode = firstNode;
            for (int i = 0; i < givenPosition - 1; ++i) {
                currentNode = currentNode.next;     // advance currentNode to next node
            }
            result = currentNode.data;  // currentNode is pointing to the node at givenPosition
    } 

    return result;
  } 

    public boolean contains(T anEntry) {
        boolean found = false;
        Node currentNode = firstNode;

        while (!found && (currentNode != null)) {
            if (anEntry.equals(currentNode.data))
                found = true;
            else
                currentNode = currentNode.next;
        } 

        return found;
    } 

  public int getLength() {
     return length;
  } 

  public boolean isEmpty() {
    boolean result;

    if (length == 0)  
        result = true;
    else
        result = false;

    return result;
  } 

  public boolean isFull() {
     return false;
  } 

  public String toString() {
    String outputStr = "";
      Node currentNode = firstNode;
        while (currentNode != null) {
            outputStr += currentNode.data + "\n";
          currentNode = currentNode.next;
        } 
        return outputStr;
  } 

    private class Node {
    private T    data; 
    private Node next; 

        private Node(T data) {
            this.data = data;
            this.next = null;
        } 

        private Node(T data, Node next) {
            this.data = data;
            this.next = next;
        } 
    } // end Node

} // end LList

患者类:

public class Patient {

    private int emergencyNo;
    private int queueTime;  
    private String patientName;
    private String patientIC;
    private String patientGender;
    private String patientTelNo;
    private String patientAdd;
    private String visitDate;

    public Patient() {
    }

    public Patient(int emergencyNo, int queueTime, String patientName, String patientIC, String patientGender, String patientTelNo, String patientAdd, String visitDate)
    {
        this.emergencyNo = emergencyNo;
        this.queueTime = queueTime;
        this.patientName = patientName;
        this.patientIC = patientIC;
        this.patientGender = patientGender;
        this.patientTelNo = patientTelNo;
        this.patientAdd = patientAdd;
        this.visitDate = visitDate;
    }

    //set methods
    public void setQueueTime(int queueTime)
    {
        this.queueTime = queueTime;
    }

    public boolean setEmergencyNo(int emergencyNo)
    {
        boolean varEmergencyNo = true;

        if (emergencyNo != 1 && emergencyNo != 2 && emergencyNo != 3)
        {
            varEmergencyNo = false;

            System.out.println("Emergency number is in invalid format!");
            System.out.println("Emergency number is either 1, 2 or 3 only!");
            System.out.println("\n");
        }

        else
        {
            this.emergencyNo = emergencyNo;
        }

        return varEmergencyNo;  
    }

    public boolean setPatientName(String patientName)
    {
        boolean varPatientName = true;

        if (patientName.equals("")  || patientName.equals(null))
        {
            varPatientName = false;

            System.out.println("The patient name cannot be empty!\n");
        }

        else
        {
            this.patientName = patientName;
        }

        return varPatientName;  
    }

    public boolean setPatientIC(String patientIC)
    {
        boolean varPatientIC = true;

        if(!patientIC.matches("^[0-9]{12}$"))
        {
            varPatientIC = false;

            System.out.println("IC is in invalid format!");
            System.out.println("It must consist of 12 numbers only!\n");
        }

        else
        {
            this.patientIC = patientIC;
        }

        return varPatientIC;
    }

    public boolean setPatientGender(String patientGender)
    {
        boolean varPatientGender = true;

        if(!patientGender.equals("F") && !patientGender.equals("f") && !patientGender.equals("M") && !patientGender.equals("m"))
        {
            varPatientGender = false;

            System.out.println("Gender is in invalid format!");
            System.out.println("It must be either 'M' or 'F' only!\n");
        }

        else
        {
            this.patientGender = patientGender;
        }

        return varPatientGender;
    }

    public boolean setPatientTelNo(String patientTelNo) 
    {
        boolean varPatientTelNo = true;

        if((!patientTelNo.matches("^01[02346789]\\d{7}$")) && (!patientTelNo.matches("^03\\d{8}$")))
        {
            varPatientTelNo = false;

            System.out.println("Invalid phone number!");
            System.out.println("It must be in the following format : 0167890990 / 0342346789!\n");
            System.out.print("\n");
        }

        else
        {
            this.patientTelNo = patientTelNo;
        }

        return varPatientTelNo;
    }

    public boolean setPatientAdd(String patientAdd)
    {
        boolean varPatientAdd = true;

        if (patientAdd.equals("")  || patientAdd.equals(null))
        {
            varPatientAdd = false;

            System.out.println("The patient address cannot be empty!\n");
        }

        else
        {
            this.patientAdd = patientAdd;
        }

        return varPatientAdd;   
    }

    public void setVisitDate(String visitDate)
    {
        this.visitDate = visitDate;
    }

    //get methods
    public int getQueueTime()
    {
        return this.queueTime;
    }

    public int getEmergencyNo()
    {
        return this.emergencyNo;
    }

    public String getPatientName()
    {
        return this.patientName;
    }

    public String getPatientIC()
    {
        return this.patientIC;
    }

    public String getPatientGender()
    {
        return this.patientGender;
    }

    public String getPatientTelNo() 
    {
        return this.patientTelNo;
    }

    public String getPatientAdd()
    {
        return this.patientAdd;
    }

    public String getVisitDate()
    {
        return this.visitDate;
    }

    @Override
    public String toString()
    {
        return (this.emergencyNo + "\t\t" + this.patientName + "\t\t" + this.patientIC + 
            "\t\t" + this.patientGender + "\t\t" + this.patientTelNo + "\t\t" + this.patientAdd + "\t\t" + this.visitDate);
    }

    public String anotherToString()
    {
        return (this.emergencyNo + "\t\t\t\t\t\t" + this.patientName + "\t\t\t " + this.visitDate);
    }
}

EmergencyCmp(Comparator)---&gt;用于分类患者的紧急号码

import java.util.Comparator;

public class EmergencyCmp implements Comparator<Patient>
{
    @Override
    public int compare(Patient p1, Patient p2) 
    {
        if(p1.getEmergencyNo() > p2.getEmergencyNo())
        {
            return 1;
        } 

        else
        {
            return -1;
        }
     }
}

QueueCmp(Comparator)---&gt;用于分类患者的到达时间

import java.util.Comparator;

public class QueueCmp implements Comparator<Patient>
{
    @Override
    public int compare(Patient p1, Patient p2) 
    {
        if(p1.getQueueTime() > p2.getQueueTime())
        {
             return 1;
        } 

        else
        {
             return -1;
        }
    }   
}

主要功能:

import java.util.Calendar;
import java.util.Scanner;
import java.util.Arrays;
import java.util.*; 

public class DSA {

    public DSA() {
    }

    public static void main(String[] args) {

        //patient's attributes
        int emergencyNo;
        int queueTime;
        String patientName;
        String patientIC;
        String patientGender;
        String patientTelNo;
        String patientAdd;
        String visitDate;

        //counter
        int j = 0;
        int x = 0;
        int y = 0;
        int z = 0;
        int count1 = 0;
        int count2 = 0;
        int count3 = 0;
        int countEnteredPatient = 1;
        int totalCount = 0;

        //calendar
        int nowYr, nowMn, nowDy, nowHr, nowMt, nowSc;

        //others
        boolean enterNewPatient = true;
        String continueInput;
        boolean enterNewPatient1 = true;
        String continueInput1;
        boolean continueEmergencyNo;

        Scanner scan = new Scanner(System.in);
        ListInterface<Patient> patientList = new LList<Patient>();
        ListInterface<Patient> newPatientList = new LList<Patient>();
        Patient[] patientArr1 = new Patient[10000];
        Patient[] patientArr2  = new Patient[10000];
        Patient[] patientArr3  = new Patient[10000];
        Patient tempoPatient;

        do{
            //do-while loop for entering new patient details after viewing patient list

            System.out.println("Welcome to Hospital Ten Stars!\n");

            do{
                //do-while loop for entering new patient details
                System.out.println("Entering details of patient " + countEnteredPatient);
                System.out.println("===================================\n");

                Calendar calendar = Calendar.getInstance();
                nowYr = calendar.get(Calendar.YEAR);
                nowMn = calendar.get(Calendar.MONTH);
                nowDy = calendar.get(Calendar.DAY_OF_MONTH);
                nowHr = calendar.get(Calendar.HOUR);
                nowMt = calendar.get(Calendar.MINUTE);
                nowSc = calendar.get(Calendar.SECOND);
                queueTime = calendar.get(Calendar.MILLISECOND);

                visitDate = nowDy + "/" + nowMn + "/" + nowYr + ", " + nowHr + ":" + nowMt + ":" + nowSc;

                //input emergency number
                do{
                    tempoPatient = new Patient();

                    continueEmergencyNo = false;
                    int EmergencyNoOption;

                    try
                    {
                        do{
                            System.out.print("Please select 1 – Immediately life threatening, 2 – Urgent, but not immediately life threatening or 3 – Less urgent(Eg: 1) : ");
                            EmergencyNoOption = scan.nextInt();
                            scan.nextLine();
                            System.out.print("\n");

                          }while(tempoPatient.setEmergencyNo(EmergencyNoOption) == false);
                    }

                    catch(InputMismatchException ex)
                    {
                        System.out.print("\n");
                        System.out.println("Invalid input detected.");
                        scan.nextLine();
                        System.out.print("\n");

                        continueEmergencyNo = true;
                    }
                  }while(continueEmergencyNo);

                  //input patient name
                  do{
                        System.out.print("Patient name(Eg: Christine Redfield) : ");
                        patientName = scan.nextLine();
                        System.out.print("\n");
                    }while(tempoPatient.setPatientName(patientName) == false);

                  //input patient ic no
                  do{
                        System.out.print("Patient IC number(Eg: 931231124567) : ");
                        patientIC = scan.nextLine();
                        System.out.print("\n");
                     }while(tempoPatient.setPatientIC(patientIC) == false);

                  //input patient gender    
                  do{
                        System.out.print("Patient gender(Eg: M) : ");
                        patientGender = scan.nextLine();
                        System.out.print("\n");
                    }while(tempoPatient.setPatientGender(patientGender) == false);

                  //input patient tel. no
                  do{
                        System.out.print("Patient tel.No(without'-')(Eg: 0162345678/0342980123) : ");
                        patientTelNo = scan.nextLine();
                        System.out.print("\n");
                    }while(tempoPatient.setPatientTelNo(patientTelNo) == false);

                  //input patient address
                  do{
                        System.out.print("Patient address(Eg: 4-C9 Jln Besar 123, Taman Besar, 56000 Kuala Lumpur) : ");
                        patientAdd = scan.nextLine();
                        System.out.print("\n");
                    }while(tempoPatient.setPatientAdd(patientAdd) == false);

                  tempoPatient.setQueueTime(queueTime);
                  tempoPatient.setVisitDate(visitDate);             
                  patientList.add(tempoPatient);

                  //decide whether want to enter a new patient or not   
                  do{
                        System.out.print("Do you want to enter another new patient?(Eg: Y/N) : ");
                        continueInput = scan.nextLine();

                        if(continueInput.equals("Y") || continueInput.equals("y"))
                        {
                            enterNewPatient = true;

                            System.out.print("\n");
                        }

                        else if(continueInput.equals("N") || continueInput.equals("n"))
                        {
                            enterNewPatient = false;
                        }

                        else
                        {   
                            System.out.println("\n");
                            System.out.println("Please enter Y/N only.\n");
                        }

                    }while(!continueInput.equals("Y") && !continueInput.equals("y") && !continueInput.equals("N") && !continueInput.equals("n"));

                countEnteredPatient++;
            }while(enterNewPatient);    //end do-while loop for entering new patient details

            System.out.println("\nWaiting list of patient will be displayed soon.\n");

            try{
                Thread.sleep(1000);

            }
            catch (Exception e)
            {

            }

            System.out.println("Waiting list of patients");
            System.out.println("========================\n");
            System.out.println("Number\t\tEmergency number\t\tPatient name\t\t ArrivalTime");
            System.out.println("============================================================================");

            for(int i = 1; i <= patientList.getLength(); i++)
            {
                System.out.println(i + "\t\t\t" + patientList.getEntry(i).anotherToString());
            }

            do{
                    System.out.print("\nSo, now do you want to enter another new patient?(Eg: Y/N) : ");
                    continueInput1 = scan.nextLine();

                    if(continueInput1.equals("Y") || continueInput1.equals("y"))
                    {
                        enterNewPatient1 = true;

                        System.out.print("\n");
                    }

                    else if(continueInput1.equals("N") || continueInput1.equals("n"))
                    {
                        enterNewPatient1 = false;
                    }

                    else
                    {
                        System.out.println("\n");
                        System.out.println("Please enter Y/N only.\n");
                    }

              }while(!continueInput1.equals("Y") && !continueInput1.equals("y") && !continueInput1.equals("N") && !continueInput1.equals("n"));

          }while(enterNewPatient1);//end do-while loop for entering new patient details after viewing patient list

        System.out.println("\nNow rearranging the list based on the seriouness and their arrival time.");

        try{
                Thread.sleep(1000);

        }
        catch (Exception e)
        {

        }

        //create an unsorted array
        Patient[] tempoPatientArr = new Patient[patientList.getLength()];

        //copy the contents of patientList into tempoPatientArr
        for(int i = 1; i <= patientList.getLength(); i++ )
        {
            tempoPatientArr[i-1] = patientList.getEntry(i);
        }

        //sort tempoPatientArr
        Arrays.sort(tempoPatientArr, new EmergencyCmp());
        //the above part until this comment line does not have problem

        //check the emergency no and then categorise accordingly
        for(int i = 0; i < tempoPatientArr.length; i++)
        {
            if(tempoPatientArr[i].getEmergencyNo() == 1)
            {
                patientArr1[x] = tempoPatientArr[i];

                x++;
            }

            else if(tempoPatientArr[i].getEmergencyNo() == 2)
            {
                patientArr2[y] = tempoPatientArr[i];

                y++;
            }

            else if(tempoPatientArr[i].getEmergencyNo() == 3)
            {
                patientArr3[z] = tempoPatientArr[i];

                z++;
            }
        }

        //to check how many !null elements by using count for 3 sub-arrays
        for(int i = 0; i < patientArr1.length; i++)
        {
            if(patientArr1[i] != null)
            {
                count1++;
            }

            else
            {
                break;
            }
        }

        for(int i = 0; i < patientArr2.length; i++)
        {
            if(patientArr2[i] != null)
            {
                count2++;
            }

            else
            {
                break;
            }
        }

        for(int i = 0; i < patientArr3.length; i++)
        {
            if(patientArr3[i] != null)
            {
                count3++;
            }

            else
            {
                break;
            }
        }

        //new array with elimination of null values
        Patient[] newPatientArr1 = new Patient[count1];
        Patient[] newPatientArr2 = new Patient[count2];
        Patient[] newPatientArr3 = new Patient[count3];

        //copy the contents of old sub arrays(the arrays with null values) into the new sub arrays(without null values)
        for(int i = 0; i < newPatientArr1.length; i++)
        {
            newPatientArr1[i] = patientArr1[i];
        }

        for(int i = 0; i < newPatientArr2.length; i++)
        {
            newPatientArr2[i] = patientArr2[i];
        }

        for(int i = 0; i < newPatientArr3.length; i++)
        {
            newPatientArr3[i] = patientArr3[i];
        }

        totalCount = count1 + count2 + count3;

        //array that used to combine all the sub-arrays
        Patient[] newPatientArr = new Patient[totalCount];

        //sort all sub new arrays
        Arrays.sort(newPatientArr1, new QueueCmp());
        Arrays.sort(newPatientArr2, new QueueCmp());
        Arrays.sort(newPatientArr3, new QueueCmp());

        //combine the contents of sub new arrays into the newPatientArr array
        do{
            for (int i = 0; i < count1; i++)
            {
                newPatientArr[j] = newPatientArr1[i];

                j++;
            }

            for (int b = 0; b < count2; b++)
            {
                newPatientArr[j] = newPatientArr2[b];

                j++;
            }

            for (int c = 0; c < count3; c++)
            {
                newPatientArr[j] = newPatientArr3[c];

                j++;
            }

        }while(j < totalCount);

        //relink the nodes
        for(int i = 0; i < newPatientArr.length; i++)
        {
            newPatientList.add(newPatientArr[i]);
        }

        System.out.println("\nSorted waiting list of patients");
        System.out.println("===============================\n");
        System.out.println("Number\t\tEmergency number\t\tPatient name\t\t ArrivalTime");
        System.out.println("============================================================================");

        for(int i = 1; i <= newPatientList.getLength(); i++)
        {
            System.out.println(i + "\t\t\t" + newPatientList.getEntry(i).anotherToString());
        }
    }
}

接口和LList类肯定没有问题。所以每个人都可以跳过这2个部分。

对于主要功能,我有这样的评论:

//the above part until this comment line does not have problem

当你们都看到评论时,这意味着前面的代码没有问题,你们都可以跳过它,下面是我之前得到的结果的附件:

enter image description here

因此,从图片中你可以看到到达时间的分类不正确。我希望我能知道为什么会出现这个问题,因为我自己无法解决这个问题。先谢谢你们所有人。

因此,在听取了@Scott Hunter的建议之后,我对EmergencyCmp进行了以下修改:

    @Override
    public int compare(Patient p1, Patient p2) 
    {
        int value = 0;

        if(p1.getEmergencyNo() > p2.getEmergencyNo())
        {
            value = 1;
        } 

        else if(p1.getEmergencyNo() < p2.getEmergencyNo())
        {
            value = -1;
        }

        else if(p1.getEmergencyNo() == p2.getEmergencyNo())
        {
            if(p1.getQueueTime() > p2.getQueueTime())
            {
                 return 1;
            } 

            else
            {
                 return -1;
            }
        }

        return value;
     }

然而,时间排序仍会产生错误的结果。

1 个答案:

答案 0 :(得分:1)

据我所知(我可能没有;你提供了很多无关紧要的东西),看起来你试图执行两个不同的排序,一个接一个,这样第二个就是撤消第一个的工作。相反,您应该定义一个Comparator来比较紧急号码,并且只有在它们相同时才比较到达时间。