小编典典

If和Else If之间的区别?

java

我想知道为什么要使用一个else if语句而不是多个if语句?例如,这样做之间有什么区别:

if(i == 0) ...
else if(i == 1) ...
else if(i == 2) ...

还有这个:

if(i == 0) ...
if(i == 1) ...
if(i == 2) ...

他们似乎做的完全一样。


阅读 391

收藏
2020-12-03

共1个答案

小编典典

if(i == 0) ... //if i = 0 this will work and skip following statement
else if(i == 1) ...//if i not equal to 0 and if i = 1 this will work and skip following statement
else if(i == 2) ...// if i not equal to 0 or 1 and if i = 2 the statement will execute


if(i == 0) ...//if i = 0 this will work and check the following conditions also
if(i == 1) ...//regardless of the i == 0 check, this if condition is checked
if(i == 2) ...//regardless of the i == 0 and i == 1 check, this if condition is checked
2020-12-03