java if else 语句有两个条件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31732981/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
if else statement with two condition
提问by stack overflow
This maybe trivial but I have this code
这可能微不足道,但我有这个代码
if(condition 1 & condition 2){
// apply some code
}
else{
// apply other code
}
my question is: When is else applied?
Is it applied when both conditions are false
or is it enough for one condition to be false
?
我的问题是:其他什么时候应用?它是在两个条件都成立时应用false
还是一个条件成立就足够了false
?
回答by Blake Yarbrough
First off, you are using bitwise andwhich I don't think does what you want.
首先,您使用的是按位,我认为这不是您想要的。
In order to use logical and (&&
) change if(condition 1 & condition 2){
to if(condition 1 && condition 2){
.
为了使用逻辑和 ( &&
)if(condition 1 & condition 2){
改为if(condition 1 && condition 2){
.
Secondly, if one condition is false
then the else will evaluate.
其次,如果有一个条件,false
则 else 将进行评估。
When using &&
in if statements the if logic evaluates if and only if both sides of the &&
evaluate to true.
&&
在 if 语句中使用时,if 逻辑评估当且仅当两边的&&
评估结果都为真。
if evaluates when:
if 评估时间:
true && true
else evaluates when:
else 在以下情况下进行评估:
false && true
true && false
false && false
回答by JFPicard
You will need a little logic here. Check the Truth table here: https://en.wikipedia.org/wiki/Truth_table
这里你需要一点逻辑。在此处检查真值表:https: //en.wikipedia.org/wiki/Truth_table
if(condition 1 && condition 2){
will enter the else if the condition of the if (condition 1 && condition 2)
is false. So the condition is false if:
如果(condition 1 && condition 2){
if 的条件(condition 1 && condition 2)
为假,则if将进入 else 。所以条件为假,如果:
condition 1 is false OR condition 2 is false
condition 1 is false OR condition 2 is false
In that case, it's the else block that will be executed.
在这种情况下,将执行 else 块。
Also, check the difference between bitwise operators since && and & are not the same thing.
另外,检查按位运算符之间的区别,因为 && 和 & 不是一回事。