[英]Java conditionals (checking for first condition within the condition)
if((x == 5) || (x == 2)) {
[huge block of code that happens]
if(x == 5)
five();
if(x == 2)
two();
}
So I'm checking for either 5 or 2. And there is a huge block of code that happens after either 5 or 2. The problem is that then I want to do different things depending on whether it is 5 or 2. I didn't want to have separate conditionals for 5 or 2 for the huge block of code (duplicating it would be unwieldy). 所以我要检查5或2。在5或2之后会发生大量代码。问题是,我想根据是5还是2做不同的事情。我没有不想为庞大的代码块分别设置5或2个条件(复制将很麻烦)。 I also didn't like the way I did it above because x
is actually really long. 我也不喜欢上面的方法,因为x
实际上很长。
Is there a way to say something like: 有没有办法像这样说:
if((x == 5) || (x == 2)) {
[huge block of code that happens]
if(first conditional was true)
five();
if(second conditional was true)
two();
}
I can always do it the way I did above. 我总是可以像上面那样做。 Just curious if such an option exists. 只是好奇是否存在这样的选择。
If the conditionals are big, ugly, and much less nice than x == 5
, then just store the results in a boolean
: 如果条件大,丑陋并且比x == 5
好得多,则只需将结果存储在boolean
:
boolean xWasFive = x == 5;
boolean xWasTwo = !xWasFive && x == 2;
if (xWasFive || xWasTwo) {
...
if (xWasFive) doA;
else if (xWasTwo) doB;
}
One way I can think of is basically to "alias" the longer boolean expressions in the if
condition: 我可以想到的一种方法基本上是在if
条件中“混淆”较长的布尔表达式:
boolean expr1, expr2;
if (expr1 = (x == 5) | expr2 = (x == 2)) {
// huge block of code that happens
if (expr1) five();
if (expr2) two();
}
I used non short-circuiting operator to ensure expr2 gets assigned. 我使用了非短路运算符来确保expr2被分配。
Only thing I can think of would be to set a flag for both options. 我唯一能想到的就是为两个选项都设置一个标志。 Sort of like this: 有点像这样:
boolean wasFive = x == 5;
boolean wasTwo = x == 2;
if(wasFive || wasTwo) {
[huge block of code that happens]
if(wasFive)
five();
if(wasTwo)
two();
}
Maybe something like this: 也许是这样的:
final boolean firstCondition = (x == 5);
final boolean secondCondition = (x == 2);
if (firstCondition || secondCondition) {
// code
if(firstCondition) {
// code
}
else if (secondCondition) {
// code
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.