确定导致if语句执行的条件

时间:2012-08-14 14:54:53

标签: java

所以我有一个if语句,如下所示:

List<Integer> portsInUse = new ArrayList<Integer>();
. . .
if(portsInUse.contains((Integer) newPort1) 
        || portsInUse.contains((Integer) newPort2){

    fail(_____, "This port is already in use.");
}
通过从HttpServletRequest中挖掘它们来分配

newPort1newPort2fail(String parameter, String message)是一种内部方法,用于提醒用户出现问题。

我想要做的是能够告诉哪个条件导致if语句触发,然后相应地设置失败消息。我可以这样做,还是我必须做这样的事情:

List<Integer> portsInUse = new ArrayList<Integer>();
. . .
boolean port1 = portsInUse.contains((Integer) newPort1);
boolean port2 = portsInUse.contains((Integer) newPort2);
if(port1 || port2){
    if(port1)
        fail("newPort1", "This port is already in use.");
    else
        fail("newPort2", "This port is already in use.");
}

或者,第三种选择,我应该打破这样的条件:

List<Integer> portsInUse = new ArrayList<Integer>();
. . .
if(portsInUse.contains((Integer) newPort1) {
    fail("newPort1", "This port is already in use.");
}
if(portsInUse.contains((Integer) newPort2) {
    fail("newPort2", "This port is already in use.");
}

我确定我过于复杂,但提前谢谢你。

4 个答案:

答案 0 :(得分:2)

第四个选项......

List<Integer> portsInUse = new ArrayList<Integer>();
. . .
if(portsInUse.contains((Integer) newPort1) {
    fail("newPort1", "This port is already in use.");
}
else if(portsInUse.contains((Integer) newPort2) {
    fail("newPort2", "This port is already in use.");
}else{
    //No ports in use
}

第五种选择......

List<Integer> portsInUse = new ArrayList<Integer>();
. . .
if(portsInUse.contains((Integer) newPort1) {
    if(portsInUse.contains((Integer) newPort2) {
        //both ports in use
    }else{
        //port 1 in use
    }
}
else if(portsInUse.contains((Integer) newPort2) {
    //Port 2 in use
}else{
    //No ports in use
}

答案 1 :(得分:0)

由于您需要确定正在使用哪个特定端口,因此第三个选项将更为理想。

答案 2 :(得分:0)

我认为你的第三个选择是最好的,因为你避免了option2 if(port1 || port2)的额外条件

答案 3 :(得分:0)

List<Integer> portsInUse = new ArrayList<Integer>();
. . .
List<Integer> portsToCheck = new ArrayList<Integer>();

portsToCheck.add(newPort1);
portsToCheck.add(newPort2);
...    

for (Integer port: portsToCheck){
    if (portsInUse.contains(port)) {
        fail(port+"", "This port is already in use.");  
    }
}