简体   繁体   English

使用for循环以正确的索引将对象添加到ArrayList

[英]Adding object to a ArrayList in a correct index using for-loop

I have a method to add a patient to the correct index depending on their priority. 我有一种方法可以根据患者的优先级将其添加到正确的索引中。 However it seems that when I add more than one person, it doesn't get added. 但是,当我添加一个以上的人时,似乎没有添加。 I'm not too sure what I'm missing in my add method. 我不太确定我的添加方法中缺少什么。 My guess is there is something wrong with the if-else statement but I'm not able to pinpoint where the problem is. 我的猜测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());
}

and if I run this test case, I would get 1 for the numWaiting for some reason... where could I have gone wrong in this code?? 如果我运行此测试用例,由于某种原因,我将得到numWaiting 1 ...在此代码中我哪里可能出错了?

After the for cycle you are not adding any patient if they have lower priority than the existing ones. for循环之后,如果优先级比现有患者低,则不添加任何患者。

As soon as you add a patient in the list you should return from the method; 在列表中添加患者后,您应该立即从方法中return if you reach the end of the method it means that the new patient has the lowest priority and you should add him at the end of the list. 如果您到达方法的末尾,则意味着新患者的优先级最低,您应该将其添加到列表的末尾。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM