Java 调用getter方法而不在if语句中指定对象

Java 调用getter方法而不在if语句中指定对象,java,Java,我正在练习使用getter和setter。我正在制作一个任务窗格,要求用户输入医院患者唯一编号并返回患者详细信息。我正在命名患者/对象p1、p2、p3等。我已经在另一个类文件中创建了getter和setter 我的问题是,如何创建一个If语句来接受任何patient对象作为输入 有没有一种方法可以让JOptionPane.showMessageDialog只调用getName、getAge等方法,而不必为每个对象/患者创建if语句?例如p2.getName、p3.getName、p4.getNa

我正在练习使用getter和setter。我正在制作一个任务窗格,要求用户输入医院患者唯一编号并返回患者详细信息。我正在命名患者/对象p1、p2、p3等。我已经在另一个类文件中创建了getter和setter

我的问题是,如何创建一个If语句来接受任何patient对象作为输入

有没有一种方法可以让JOptionPane.showMessageDialog只调用getName、getAge等方法,而不必为每个对象/患者创建if语句?例如p2.getName、p3.getName、p4.getName等

import java.util.Scanner;
import javax.swing.JOptionPane;

public class Main {

    public static void main(String[] args) {

        Person p1 = new Person();
        p1.setpatientNumber(001);
        p1.setName("David");
        p1.setYearOfBirth(1983);
        p1.setFather("Mike");
        p1.setMother("Unknown");

        Person p2 = new Person();
        p2.setpatientNumber(002);
        p2.setName("Simon");
        p2.setYearOfBirth(1979);
        p2.setFather("John");
        p2.setMother("Mary");

        Scanner keyboard = new Scanner(System.in);

        int input = Integer.parseInt(JOptionPane.showInputDialog("Enter the patient number"));
        if (p1.getpatientNumber() == input) {
        JOptionPane.showMessageDialog(null, "Patient details:\n" + p1.getName() + "\n" + p1.getYearOfBirth() + "\n" + p1.getFather() + "\n" + p1.getMother());
        }else{
            JOptionPane.showMessageDialog(null, "Unknown number");
        }
    }
}
您可以将所有Person对象添加到ArrayList中,然后对其进行迭代

ArrayList<Person> persons = new ArrayList<Person>;

//Create your persons

persons.add(p1);
persons.add(p2);

//Get input

//Iterate over all persons in the persons ArrayList
for (Person p : persons) {
    if (p.getPatientNumber() == input) {
        JOptionPane.showMessageDialog(null, "Patient details:\n" + p.getName() + "\n" + p.getYearOfBirth() + "\n" + p.getFather() + "\n" + p.getMother());
    }
}

如果您已经知道患者的大小,请将患者存储在列表或数组中,然后迭代整个列表。比如:

List<Person> personList = new ArrayList<Person>();
personList.add(p1);
personList.add(p2);

注意:您应该使用1/2/3作为患者id,而不是001等,因为从0开始的数字在Java中被视为八进制值。

创建一个Person集合。循环。从你提出问题的方式来看,这听起来像是来自学校的课堂。答案是需要使用集合或数组。您可能还没有在课程中涵盖此主题。有了这样的作业,我想很快就会有课了。
for (Person person : personList) {
    if (person.getpatientNumber() == input) {
         JOptionPane.showMessageDialog(null, "Patient details:\n" + p1.getName() + "\n" + p1.getYearOfBirth() + "\n" + p1.getFather() + "\n" + p1.getMother());
     }    
 }