有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

If和elseif之间的java差异?

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

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

这是:

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

他们似乎做了完全相同的事情


共 (6) 个答案

  1. # 1 楼答案

    如果您使用了多个if语句,那么如果条件是true,那么所有语句都将被执行。如果您使用了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");
    }
    
  2. # 2 楼答案

    if语句检查所有多个可用的if。 当else if语句失败时,if语句返回true,但它不会检查else if

    因此,这取决于您的需求如何

  3. # 3 楼答案

    第一个示例不一定会运行3个测试,第二个示例不会给出任何返回或goto

  4. # 4 楼答案

    区别在于,如果第一个if为真,那么所有其他else if都不会执行,即使它们的计算结果为真。然而,如果它们是单个的if,那么如果它们的计算结果为true,那么所有的if都将被执行

  5. # 5 楼答案

    if(i == 0) ... //if i = 0 this will work and skip the following else-if statements
    else if(i == 1) ...//if i not equal to 0 and if i = 1 this will work and skip the following else-if 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
    
  6. # 6 楼答案

    对于第一种情况:一旦else if(或if)成功,剩余的else if将不进行测试。然而,在第二种情况下,即使所有(或其中一个)都成功,每个if都将进行测试