Ros*_*oss -1 java if-statement chained
通过阅读Oracle iLearning Java课程,我的印象是使用'chained if construct'相当于使用'&&'运算符.所以:
if((5 < 10) && (5 < 6)) {
run some code;
}
Run Code Online (Sandbox Code Playgroud)
是相同的:
if(5 < 10) {
if(5 < 6) {
run some code;
}
}
Run Code Online (Sandbox Code Playgroud)
比较两者,我觉得很难相信.我想我很误解.
我们可以将此代码重写为:
if(someCondition)` {
if(otherCondition) {
//code
}
}
Run Code Online (Sandbox Code Playgroud)
因此,无论someCondition
和otherCondition
对必须是真实的//code
来运行.(关键词AND).所以在这个例子if(someCondition && otherCondition)
中等同于上面的代码
通常你会使用嵌套的原因if
是你想要检查多个条件,例如:
if(someCondition) {
if(otherCondition1) {
//code
}
else if(otherCondition2) {
//code
} else {
//else
}
}
Run Code Online (Sandbox Code Playgroud)