3.18Java条件语句

3.18Java条件语句

本章内容

  • if语句

  • if...else语句


if语句

特点:

  • 一个if语句包含一个布尔表达式和一条或多条语句

语法:

if(布尔表达式)
{
   //如果布尔表达式为true将执行的语句
   //如果布尔表达式不为true将执行if语句块后面的代码
}
public class If_Practice_code
{
   public static void main(String arguments[])
  {
       int x = 10;

       if ( x < 20 )
      {
           x++;
           System.out.print("This is an If sentence" + x);
      }
  }
}

if...else语句

特点:

  • if语句的布尔表达式值为false时,else语句块会被执行

语法:

if(布尔表达式){
   //如果布尔表达式的值为true
}else{
   //如果布尔表达式的值为false
}

实例:

public class if_else_Practice_code {

   public static void main(String arguments[]) {

       for (int x = 1; x < 20; x++){
           if (x < 20) {
               System.out.print("This is an if sentence");
               System.out.print("\n");
          } else {
               System.out.print("This is not an if sentence");
               System.out.print("\n");
          }
      }
  }
}

if...else if...else语句

特点:

  • if语句至多有1个else语句,else语句在所有的else if语句之后

  • if语句可以有若干个else if语句,它们必须在else语句之前

  • 一旦其中一个 else if 语句检测为 true,其他的 else if 以及 else 语句都将跳过执行

语法:

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

实例:

public class If_eles_if_else_Practice_code {
   public static void main(String arguments[]){

       for( int x = 10; x <= 30; x++){
           if( x == 20){
               System.out.print("This is a sentence when x value is 20");
               System.out.print("\n");
          }else if( x == 30 ){
               System.out.print("This is a sentence when x value is 30");
               System.out.print("\n");
          }
      }
  }
}

嵌套的if...else语句

特点:

  • 使用嵌套的 if…else 语句是合法的。也就是说你可以在另一个 if 或者 else if 语句中使用 if 或者 else if 语句

语法:

if(布尔表达式1){
   //如果布尔表达式1的值为true执行代码
   if(布尔表达式2){
       //如果布尔表达式2的值为true执行代码
  }
}
/*
可以像if语句一样嵌套else if...else
*/

实例:

public class if_else_in_if_else_Practice_code {

   public static void main(String arguments[]){
       int x = 10;
       int y = 20;

       if( x == 10 ){
           if( y == 20 ){
               System.out.print("x = " + x);
               System.out.print("\n");
               System.out.print("y = " + y);
          }
      }
  }
}

 

posted @ 2021-03-22 09:36  俊king  阅读(16)  评论(0编辑  收藏  举报