if((x == 5) || (x == 2)) {
[huge block of code that happens]
if(x == 5)
five();
if(x == 2)
two();
}
所以我正在检查5或2.并且在5或2之后会发生大量代码。问题是我想根据它是5还是2来做不同的事情。我不想为大块代码提供5或2的单独条件(复制它会很笨重)。我也不喜欢我上面的方式,因为x
实际上很长。
有没有办法说出类似的话:
if((x == 5) || (x == 2)) {
[huge block of code that happens]
if(first conditional was true)
five();
if(second conditional was true)
two();
}
我总能像上面那样做。只是好奇这样的选择是否存在。
答案 0 :(得分:3)
如果条件很大,很丑,并且不如x == 5
好,那么只需将结果存储在boolean
中:
boolean xWasFive = x == 5;
boolean xWasTwo = !xWasFive && x == 2;
if (xWasFive || xWasTwo) {
...
if (xWasFive) doA;
else if (xWasTwo) doB;
}
答案 1 :(得分:2)
我能想到的一种方法基本上是“混淆”if
条件中较长的布尔表达式:
boolean expr1, expr2;
if (expr1 = (x == 5) | expr2 = (x == 2)) {
// huge block of code that happens
if (expr1) five();
if (expr2) two();
}
我使用非短路运算符来确保指定expr2。
答案 2 :(得分:0)
我唯一能想到的就是为两个选项设置一个标志。有点像这样:
boolean wasFive = x == 5;
boolean wasTwo = x == 2;
if(wasFive || wasTwo) {
[huge block of code that happens]
if(wasFive)
five();
if(wasTwo)
two();
}
答案 3 :(得分:0)
也许是这样的:
final boolean firstCondition = (x == 5);
final boolean secondCondition = (x == 2);
if (firstCondition || secondCondition) {
// code
if(firstCondition) {
// code
}
else if (secondCondition) {
// code
}
}