一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

java if else条件语句用法

时间:2011-05-08 编辑:简简单单 来源:一聚教程网

 if...else条件语句是条件语句最常用的一种形式,它针对某种条件有选择地做出处理。通常表现为“如果满足某种条件,就进行某种处理,否则就进行另一种处理”。

语法

if (booleanExpression) {
    statement (s)
}
 
or
 
if (booleanExpression) {
    statement (s)
} else {
    statement (s)
}

 
如,在以下如果声明中,如果块会被执行,如果x大于4。

 

public class MainClass {

  public static void main(String[] args) {
    int x = 9;
    if (x > 4) {
      // statements
    }
  }

}

在以下的例子中,如果块会被执行,如果一个比3。否则,其它的块会被执行。

public class MainClass {

  public static void main(String[] args) {
    int a = 3;
    if (a > 3) {
      // statements
    } else {
      // statements
    }
  }

}

如果表达式太长了,你可以用两个单位的缩进为后续的台词。

public class MainClass {

  public static void main(String[] args) {
    int numberOfLoginAttempts = 10;
    int numberOfMinimumLoginAttempts = 12;
    int numberOfMaximumLoginAttempts = 13;
    int y = 3;

    if (numberOfLoginAttempts < numberOfMaximumLoginAttempts
        || numberOfMinimumLoginAttempts > y) {
      y++;
    }
  }

}

如果只有一个语句

public class MainClass {

  public static void main(String[] args) {
    int a = 3;
    if (a > 3)
      a++;
    else
      a = 3;
  }

}

考虑一下这个例子:

 

public class MainClass {

  public static void main(String[] args) {
    int a = 3, b = 1;

    if (a > 0 || b < 5)
      if (a > 2)
        System.out.println("a > 2");
      else
        System.out.println("a < 2");
  }

}

多个if else

public class MainClass {

  public static void main(String[] args) {
    int a = 3, b = 1;

    if (a > 0 || b < 5) {
      if (a > 2) {
        System.out.println("a > 2");
      } else {
        System.out.println("a < 2");
      }
    }
  }

}

热门栏目