【问题标题】:Filtering an arraylist using a method使用方法过滤数组列表
【发布时间】:2013-07-28 18:53:34
【问题描述】:

我正在尝试根据用户给出的日期返回有患者的医生列表。但是每次我运行该方法时,它都会返回所有医生的列表,而不是被过滤掉。

主代码

public void printDoctorsWithPatientsOnDate() throws ParseException
{
    ArrayList<String> docs = new ArrayList();
    System.out.print("Enter the date(mm-dd-yyyy): ");
    Date dt = new SimpleDateFormat("MM-dd-yyyy").parse(sc.nextLine());
    docs = app.getDoctorsWithPatientsOnDate(dt);
    for(String i : docs)
    {
    System.out.println(i);
    }
}

过滤方法

public ArrayList<String> getDoctorsWithPatientsOnDate(Date date)
{
    ArrayList<String> doctors = new ArrayList();
    for(Patient i : patientList)
    {
        if(i.searchDatesForDoc(date) == true);
        {
            doctors.add(i.getDoctorName());
        }
    }
    return doctors;
}

查找患者日期的方法

public boolean searchDatesForDoc(Date date){
    for(Date i : datesOfVisit)
    {
        if(i.equals(date))
        {
        return true;
        }
    }
    return false;
}

我已经初始化了 2 个患者,即患者 1 和患者 2。患者 1 的医生名为 dr.lee,患者 2 的医生名为 dr.james。首先,我为患者 1 输入以下信息,然后我让患者 2 什么都没有(现在)。

Enter the Patient's name: patient1
Enter the assessment: alz
Enter the date of Visit(mm-dd-yyyy): 10-02-2010

当我得到医生名单时,问题就来了。即使日期错误,它也会继续打印列表中的每个医生。

Enter the date(mm-dd-yyyy): 11-20-2012
dr.lim
dr.james

【问题讨论】:

  • if (i.serachDatesForDoc(date)==true) - 你不需要==true。由于searchDatesForDoc 返回一个布尔值,您可以将其用作条件。我怀疑这是你的问题 - 我不明白为什么会这样 - 但它可能会有所帮助。
  • @MrB 我试过你说的,但什么也没发生。我仍然有同样的问题..

标签: java list search methods filter


【解决方案1】:

出于某种未知原因(无论如何对我而言),我给出的已接受答案已被版主删除。 这个问题已经解决。问题是他在 if 语句后面多了一个分号。

【讨论】:

    【解决方案2】:

    我没有要重现的所有代码,但我会首先关注 searchDatesForDoc 方法。试试这个:

    public ArrayList<String> getDoctorsWithPatientsOnDate(Date date)
    {
        ArrayList<String> doctors = new ArrayList();
        for(Patient i : patientList)
        {
            System.out.println("Current patient is: " + i.getPatientName());
            if(i.searchDatesForDoc(date) == true);
            {
                doctors.add(i.getDoctorName());
            }
        }
        return doctors;
    }
    
    public boolean searchDatesForDoc(Date date){
        for(Date i : datesOfVisit)
        {
            if(i.equals(date))
            {
                System.out.println("\tVisited on day: " + i);
            return true;
            }
        }
        return false;
    }
    

    当您添加这两行时,它会打印患者姓名以及患者就诊的日期。首先要检查的是患者是否确实在列出的日期进行了访问。如果没有,那么你的问题就在那里。使用调试器跟踪代码的每个步骤会更容易调试。

    【讨论】:

    • 试过你所说的,这是输出。我输入了错误的日期,它仍然打印医生大声笑输入日期(mm-dd-yyyy):10-02-2010 当前患者是:患者1 当前患者是:患者 2 dr.lim dr.james
    • 现在尝试将System.out.println("Current... 命令移动到if 语句中(因此将其向下移动两行)。让我们知道它的作用。
    猜你喜欢
    • 2021-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-22
    • 1970-01-01
    • 2015-08-30
    • 1970-01-01
    相关资源
    最近更新 更多