【问题标题】:How can i search an arrray of object with a value in java如何在java中搜索具有值的对象数组
【发布时间】:2014-12-06 12:11:58
【问题描述】:

我有两个名为 Patient Class 和 Client Class 的类。我在患者类中创建了方法并在客户端类中调用它们。我想添加一种方法来通过其 id 查找输入的记录并显示它。我的应用程序需要进行哪些更改。程序如下:

病人分类

import javax.swing.*;

public class Patient {
    private String patientname;
    private String fathername;
    private String date;
    private int dob;
    private static int id = 9000;
    private String disease;
    private String n;
    private double nic;
    private String doctorname;
    private String prescription;
    private String history;
    private String searchid;
    private int storesearchid;

    Patient() {}
    public void setPatientInformation() {

        id++;
        patientname = JOptionPane.showInputDialog("Enter Patient name: ");
        fathername = JOptionPane.showInputDialog("Enter Father name of patient: ");
        date = JOptionPane.showInputDialog("Enter date of birth : ");
        dob = Integer.parseInt(date);
        disease = JOptionPane.showInputDialog("Enter disease: ");
        n = JOptionPane.showInputDialog("Enter nic no: ");
        nic = Integer.parseInt(n);
        doctorname = JOptionPane.showInputDialog("Enter your doctor name: ");
        prescription = JOptionPane.showInputDialog("Enter description of disease: ");
        history = JOptionPane.showInputDialog("Enter history of disease? ");

    }
    public void showPatientInformation() {
        JOptionPane.showMessageDialog(null, "Patient Id" + id + "\nPatient Name: " + patientname + "\nPatient Father Name: " + fathername + "\nPatient Date of birth: " + dob + "\nDisease: " + disease + "\nNIC No:" + nic + "\nDoctor Name: " + doctorname + "\nPrescription: " + prescription + "\nHistory: " + history);
    }
    public void SearchByPatientId() {
        searchid = JOptionPane.showInputDialog("Enter Id of Patient.");
        storesearchid = Integer.parseInt(searchid);

        if (storesearchid == obj[id]) {
            JOptionPane.showMessageDialog(null, "Record Found");
        } else {
            JOptionPane.showMessageDialog(null, "Record With This Id Not Found.");
        }
    }
}

客户端类

import javax.swing.*;

public class Client {
    public static void main(String[] aa) {
        String input;
        int i = 0, op = 0;

        Patient[] obj = new Patient[50];


        obj[i] = new Patient();

        while (op != 3) {
            input = JOptionPane.showInputDialog("Press 1 for Add new Patient Record.\nPress 2 for search Record  by patient ID.\nPress 3 for exit.");
            op = Integer.parseInt(input);

            switch (op) {
                case 1:

                    JOptionPane.showMessageDialog(null, "Enter New Record");
                    obj[i].setPatientInformation();

                    JOptionPane.showMessageDialog(null, "Record added SuccessFully.");
                    obj[i].showPatientInformation();
                    break;

                case 2:
                    JOptionPane.showMessageDialog(null, "Search Record By patient ID.");
                    obj[i].SearchByPatientId();
                    break;

            }
        }
    }
}

【问题讨论】:

  • 请问您可以格式化您的代码吗?这不是很可读。
  • 这是非常糟糕的设计,你的类完全依赖于 UI 技术。您的构造函数应该接受参数,然后应该使用用户输入的数据调用
  • 我是java编程的初学者
  • @aami 您应该阅读一下ModelViewController 模式:将 UI 代码保留在底层模型之外是个好主意。

标签: java methods arrayobject


【解决方案1】:

几个变化:

  • 将obj[i] = new Patient(); 带入 for 循环,例如:

    while (op != 3) {
        obj[i++] = new Patient();
    
  • 在情况 1 中,如果 i 超过 49,则不允许用户添加数据。如果您希望允许多个元素,您可以使用 LinkedList 代替 Patient 的数组。

  • 奇怪的方式,因为它设计得不好,但修改案例2如下:

    case 2:
        JOptionPane.showMessageDialog(null, "Search Record By patient ID.");
        obj[i].SearchByPatientId(obj);
        break;
    

然后在您的搜索方法中,像这样遍历专利:

public void SearchByPatientId(Patient[] patient) {
    //take input from user
    for (Patient patient : patient) {
        if (patient.id == storesearchid){
            //found.. do whatever you want
            break;
        }
    }

【讨论】:

    【解决方案2】:

    id 不能是 static 值,因为 static 值在类的多个实例中保持相同...

    public int getID(){
        return id;
    }
    

    【讨论】:

      【解决方案3】:

      您的代码有问题

      查看您的设计后,我可以立即发现问题;患者类中不应存在任何 UI 代码。这是因为您的患者类应该仅用于访问患者信息。

      因此,我修改并添加了文档到您的患者类,以便 (1) 在公共构造函数中初始化您的类属性 (2) 提供对这些属性的公共读取访问权限 (3) 删除应该存在于其他地方的所有 UI 代码例如在您的客户端类或您从客户端类创建和访问以供用户输入的视图类中。

      患者分类

      /**
      * The patient class is used for storing the information
      * associated with a patient. 
      */
      public class Patient {
          private String patientname;
          private String fathername;
          private String date;
          private int dob;
          private static instanceCount = 0;
          private int id = 9000;
          private String disease;
          private String n;
          private double nic;
          private String doctorname;
          private String prescription;
          private String history;
      
          /**
          * This method provides a public constructor for creating a patient instance.
          *
          * @param aPatientName The name of the patient instance to be created
          * @param aFatherName The name of the father of the patient instance to be created
          * @param aDate The date associated with the patient instance to be created
          * @param aDob The DOB associated with the patient instance to be created
          * @param aDisease The disease associated with the patient instance to be created
          * @param aN The N associated with the patient instance to be created
          * @param aNic The NIC number associated with the patient instance to be created
          * @param aPrescription The prescription associated with the patient instance to be created
          * @param aHistory The history associated with the patient instance to be created
          *
          * @return a Patient instance that has been populated with the input parameters
          */
          public Patient(String aPatientName, String aFatherName, String aDate, int aDob,
                      String aDisease, String aN, double aNic, String aPrescription,
                      String aHistory) {
      
              // Increment the count for the number of patient instance that exist
              // because static variables are shared across the class itself rather
              // than the actual objects. Consequently, this count is reflected across
              // all patient instances.
              instanceCount++;           
      
              // Increment the current id so that we get a new id for this patient instance
              id = id + instanceCount;
      
              // Initialize the values of all patient attributes according to constructor parameters
              patientname = aPatientName;
              fathername = aFatherName;
              date = aDate;
              dob = aDob;
              disease = aDisease;
              n = aN;
              nic = aNic;
              prescription = aPrescription;
              history = aHistory;
          }
      
          /**
          * This method retrieves the string needed for displaying all of this
          * patient’s attributes to the user.
          * @return a String containing the attributes for this patient
          */
          public String showPatientInformation() {
              String attributes = “”;
      
              attributes += “Patient Id” + id;
              attributes += “\nPatient Name: “ + patientname;
              attributes += “\nPatient Father Name: “ + fathername;
              attributes += “\nPatient Date of Birth: “ + dob;
              attributes += “\nDisease: “ + disease;
              attributes += “\nNIC No:” + nic;
              attributes += “\nDoctor Name: “ + doctorname;
              attributes += “\nPrescription: “ + prescription;
              attributes += “\nHistory: “ + history;
      
              return attributes;
          }
      
          /**
          * This method acquires the ID of this patient instance.
          * @return int The ID of this patient instance
          */
          public int getId() {
              return id;
          }
      
          /**
          * This method acquires the name of this patient instance.
          * @return String The name of this patient instance
          */
          public String getPatientName() {
              return patientName;
          }
      
          /**
          * This method acquires the name of the father of this patient instance.
          * @return String The name of the father of this patient instance
          */
          public String getFatherName() {
              return fathername;
          }
      
          /**
          * This method acquires the date for this patient instance.
          * @return String The date for this patient instance
          */
          public String getDate() {
              return date;
          }
      
          /**
          * This method acquires the DOB of this patient instance.
          * @return int The DOB of this patient instance
          */
          public int getDob() {
              return dob;
          }
      
          /**
          * This method acquires the disease of this patient instance.
          * @return String The disease of this patient instance
          */
          public String getDisease() {
              return disease;
          }
      
          /**
          * This method acquires the N of this patient instance.
          * @return String The N of this patient instance
          */
          public String getN() {
              return n;
          }
      
          /**
          * This method acquires the NIC of this patient instance.
          * @return int The NIC of this patient instance
          */
          public double getNic() {
              return nic;
          }
      
          /**
          * This method acquires the name of the doctor for this patient instance.
          * @return String The name of the doctor for this patient instance
          */
          public String getDoctorName() {
              return doctorname;
          }
      
          /**
          * This method acquires the prescription of this patient instance.
          * @return String The prescription of this patient instance
          */
          public String getPrescription() {
              return prescription;
          }
      
          /**
          * This method acquires the history of this patient instance.
          * @return String The history of this patient instance
          */
          public String getHistory() {
              return history;
          }   
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-05-26
        • 2021-10-28
        • 1970-01-01
        • 2011-05-06
        • 2018-08-09
        • 2021-12-12
        • 2021-11-27
        相关资源
        最近更新 更多