if else条件语句

Java 条件语句

  • if
  • if…else
  • if…else if…else
  • if…else嵌套

if

语法格式:

if(表达式){
    //如果表达式结果位true 那么执行这里的代码
}

示例

public class Test {

   public static void main(String args[]){ int x = 10; if( x < 20 ){ System.out.print("这是 if 语句"); } } } 

if…else

语法格式:

if(布尔表达式){
    //true
}else{
    //false
}

示例

public class Test {

   public static void main(String args[]){ int x = 30; if( x < 20 ){ System.out.print("这是 if 语句"); }else{ System.out.print("这是 else 语句"); } } } 


if…else if…else


语法格式:

if(布尔表达式 1){
   //如果布尔表达式 1的值为true执行代码
}else if(布尔表达式 2){
   //如果布尔表达式 2的值为true执行代码
}else if(布尔表达式 3){
   //如果布尔表达式 3的值为true执行代码
}else {
   //如果以上布尔表达式都不为true执行代码
}

注意:

  1. 最多有一个else语句
  2. 可以有若干个else if语句,但必须再else之前
  3. 一旦其中一个else if语句检测为true,其他的else if以及else都会被跳过。

示例

public class Test {
   public static void main(String args[]){ int x = 30; if( x == 10 ){ System.out.print("Value of X is 10"); }else if( x == 20 ){ System.out.print("Value of X is 20"); }else if( x == 30 ){ System.out.print("Value of X is 30"); }else{ System.out.print("这是 else 语句"); } } } 

if…else嵌套

语法格式:

if(布尔表达式 1){
   ////如果布尔表达式 1的值为true执行代码
   if(布尔表达式 2){
      ////如果布尔表达式 2的值为true执行代码
   }
}

示例

public class Test {

   public static void main(String args[]){ int x = 30; int y = 10; if( x == 30 ){ if( y == 10 ){ System.out.print("X = 30 and Y = 10"); } } } } 

猜你喜欢

转载自www.cnblogs.com/bomily0212/p/12082966.html