If和Else之间的区别如果?

spa*_*ama 26 java if-statement

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

if(i == 0) ...
else if(i == 1) ...
else if(i == 2) ...
Run Code Online (Sandbox Code Playgroud)

还有这个:

if(i == 0) ...
if(i == 1) ...
if(i == 2) ...
Run Code Online (Sandbox Code Playgroud)

他们似乎完全一样.

Dam*_*ran 50

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
Run Code Online (Sandbox Code Playgroud)


Mul*_*er0 9

不同之处在于,如果第一个if为真,则所有其他ifs都不会被执行,即使它们的评估结果为真.if但是,如果它们是个体s,if那么如果它们评估为真,则所有s都将被执行.


Dee*_*pak 9

如果您使用了多个if语句,那么如果条件为trueall 则将执行。如果您使用了ifelse if组合,则只会在第一个出现真值的地方执行

// if condition true then all will be executed
if(condition) {
    System.out.println("First if executed");
}

if(condition) {
    System.out.println("Second if executed");
}

if(condition) {
    System.out.println("Third if executed");
}


// only one will be executed 

if(condition) {
   System.out.println("First if else executed");
}

else if(condition) {
   System.out.println("Second if else executed");
}

else if(condition) {
  System.out.println("Third if else executed");
}
Run Code Online (Sandbox Code Playgroud)