【问题标题】:Adding object to a ArrayList in a correct index using for-loop使用 for 循环将对象添加到正确索引中的 ArrayList
【发布时间】:2019-04-13 23:10:54
【问题描述】:

我有一种方法可以根据患者的优先级将患者添加到正确的索引中。但是,似乎当我添加一个以上的人时,它并没有被添加。我不太确定我的 add 方法中缺少什么。我的猜测是 if-else 语句有问题,但我无法确定问题出在哪里。

public void addPatient(Patient sickPerson)
{
    int lim = patients.size();

    if (patients.isEmpty()) //if empty
    {
        patients.add(sickPerson);
    }
    else //if not empty
    {
        for (int i = 0; i < lim; i++) 
        {
        if (patients.get(i).compareTo(sickPerson) > 0) 
            // if the sickperson is more important...
            {
                patients.add(i, sickPerson);
            } 

        else if (patients.get(i).compareTo(sickPerson) == 0)
            // if the sickperson's priority is the same, 
            {
                patients.add(i + 1, sickPerson);
            }
        else 
            {
                continue;
            }
        }
    }

}

@Test
public void getNumWaitingTest() {

    WaitingRoom a = new WaitingRoom();
    Patient b = new Patient("name", "bad", 1, 1);
    Patient c = new Patient("name2", "bad2", 2, 2);

    a.addPatient(b);
    a.addPatient(c);

    assertEquals(2, a.getNumWaiting());
}

如果我运行这个测试用例,出于某种原因,我会得到 1 的 numWaiting... 这段代码哪里出错了?

【问题讨论】:

    标签: java arraylist add


    【解决方案1】:

    for 循环之后,如果患者的优先级低于现有患者,则您不会添加任何患者。

    在列表中添加患者后,您应该从方法中return;如果您到达方法的末尾,则意味着新患者的优先级最低,您应该将他添加到列表的末尾。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-05
      • 2018-05-19
      • 2014-04-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多