Java 条件(检查条件中的第一个条件)
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();
}
我总是可以像上面那样做。只是好奇是否存在这样的选择。
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). I also didn't like the way I did it above because x
is actually really long.
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我能想到的一种方法基本上是在 if 条件中“别名”较长的布尔表达式:
我使用非短路运算符来确保 expr2 被分配。
One way I can think of is basically to "alias" the longer boolean expressions in the
if
condition:I used non short-circuiting operator to ensure expr2 gets assigned.
也许是这样的:
Maybe something like this:
我唯一能想到的就是为这两个选项设置一个标志。有点像这样:
Only thing I can think of would be to set a flag for both options. Sort of like this:
如果条件又大又难看,而且远不如 x == 5 好,那么只需将结果存储在布尔值中即可:
If the conditionals are big, ugly, and much less nice than
x == 5
, then just store the results in aboolean
: