【问题标题】:Set status in java在java中设置状态
【发布时间】:2021-02-27 21:30:14
【问题描述】:

所以我编写了这部分应用程序。它有效,但并非一直有效。

public void setStatus(int id, int area, boolean free)
{
    Iterator<Ambulance> ab = cars.iterator();
    while(ab.hasNext()){
        Ambulance ambulance = ab.next();
        if(ambulance.getID() == id){
            ambulance.moveTo(area);
            ambulance.setBusy();
        }  
    }

}

对于这个 setStatus,我有这个测试条件,但是条件的这部分assertEquals(!oldStatus, selected.isFree()); 不起作用。我该怎么办?

public void moveAmbulance()
{
    // Select a random Ambulance to be moved.
    Ambulance selected = shadow.get(rand.nextInt(shadow.size()));
    int oldArea = selected.getArea();
    boolean oldStatus = selected.isFree();
    control.setStatus(selected.getID(), oldArea + 1, !oldStatus);
    assertEquals(oldArea + 1, selected.getArea());
    assertEquals(!oldStatus, selected.isFree());
}

【问题讨论】:

  • 无关:您可以将while 循环替换为增强的for 循环:for (Ambulance ambulance : cars) { … }

标签: java iterator


【解决方案1】:

你不要在setStatus方法中使用free参数

public void setStatus(int id, int area, boolean free)
{
    Iterator<Ambulance> ab = cars.iterator();
    while(ab.hasNext()){
        Ambulance ambulance = ab.next();
        if ((free) && (ambulance.getID() == id)) {
            ambulance.moveTo(area);
            ambulance.setBusy();
        }  
    }
}

【讨论】:

    【解决方案2】:
    public void setStatus(int id, int area, boolean free)
    {
        Iterator<Ambulance> ab = cars.iterator();
        while(ab.hasNext()){
            Ambulance ambulance = ab.next();
            if(ambulance.getID() == id){
                ambulance.moveTo(area);
            }
            if(free){
                ambulance.setFree();
            } else{
                ambulance.setBusy();
            }
            
        }
    }
    

    【讨论】:

    • 你需要写一个关于你的代码的简短描述来解释你做了什么。
    猜你喜欢
    • 1970-01-01
    • 2021-03-26
    • 1970-01-01
    • 2021-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多