gpt4 book ai didi

java - 确定哪个条件导致 if 语句执行

转载 作者:行者123 更新时间:2023-11-30 09:33:59 24 4
gpt4 key购买 nike

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

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

fail(_____, "This port is already in use.");
}

newPort1newPort2 是通过从 HttpServletRequest 中挖掘出来分配的。 fail(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.");
}

我确定我把事情复杂化了,但提前谢谢你。

最佳答案

第四个选项...

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
}

关于java - 确定哪个条件导致 if 语句执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11955072/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com