问题描述
如果你有这样的代码:
if (a > x && b > y) { action1(); } else if(a > x || b > y) { action2(); }
使用 a >x 和 b >y,if-else-if 梯形图的两个部分都会执行吗?
with a > x and b > y, will both parts of the if-else-if ladder be executed?
我正在处理存在这种情况的 java 代码.我通常使用 c 工作,但我是一个非常新的(和零星的)两种语言的程序员.
i'm dealing with java code where this is present. i normally work in c , but am an extremely new (and sporadic) programmer in both languages.
推荐答案
不,它们不会同时执行.它按照您编写它们的顺序排列,从逻辑上讲这是有道理的;即使第二个读作else if",您仍然可以将其视为else".
no, they won't both execute. it goes in order of how you've written them, and logically this makes sense; even though the second one reads 'else if', you can still think of it as 'else'.
考虑一个典型的 if/else 块:
consider a typical if/else block:
if(true){ // blah } else{ // blah blah }
如果您的第一个陈述是正确的,那么您甚至不必费心查看在 else 情况下需要做什么,因为它是无关紧要的.同样,如果你有'if/elseif',你就不会浪费时间查看后续的块,因为第一个是真的.
if your first statement is true, you don't even bother looking at what needs to be done in the else case, because it is irrelevant. similarly, if you have 'if/elseif', you won't waste your time looking at succeeding blocks because the first one is true.
一个真实的例子可能是分配成绩.你可以试试这样的:
a real world example could be assigning grades. you might try something like this:
if(grade > 90){ // student gets a } else if(grade > 80){ // student gets b } else if(grade > 70){ // student gets c }
如果学生得到了 99%,那么所有这些条件都是正确的.但是,您不会分配学生 a、b 和 c.
if the student got a 99%, all of these conditions are true. however, you're not going to assign the student a, b and c.
这就是为什么顺序很重要.如果我执行了这段代码,并将 b 块放在 a 块之前,那么您将为同一个学生分配 b 而不是 a,因为不会执行 a 块.
that's why order is important. if i executed this code, and put the b block before the a block, you would assign that same student with a b instead of an a, because the a block wouldn't be executed.