10、流程控制(一)

在一个程序执行的过程中,各条语句的执行顺序对程序的结果有直接影响。也就是说,程序的流程对运行结果,有直接的影响。所以,我们必须倾出每条语句的执行语句,而且,很多时候我们要通过通知语句的执行顺序来实现我们要完成的功能。

10.1 顺序结构

1 public class shunxu{
2   public static void main(String[] args){
3     System.out.println("Hello");
4     System.out.println("World");
5   }
6 }

顺序结构流程图:

 10.2 判断语句(选择结构)

  10.2.1 if语句

    

1 if(关系表达式){
2   语句体;
3 }

  执行流程:

    1.首先判断条件是true还是false

    2.是true则执行

    3.是false则不执行

  执行流程图:

public class IF{
  public static void main(String[] args){
    System.out.println("今天天气不错,正在压马路,突然出现一个和快乐的地方:网吧");
    int age = 16;
    if(age >= 18);{
      System.out.println("进入网吧,开始快乐!!!");
    }  
  }
}

  10.2.2 if...else语句

  

if(关系表达式){
   语句体1  
}else{
  语句体2
}

  执行流程:

    1.首先判断关系表达式是ture还是false

    2.是true则执行语句体1

    3.是false则执行语句体2

  执行流程图:

  二者选其一:

 1 public class Ifelse{
 2   public static void main(String[] args){
 3     int num = 13;
 4 
 5     if(num % 2 == 0){
 6       System.out.println("偶数");
 7     }else{
 8       System.out.println("奇数");
 9     }
10   }
11 }

  10.2.3 扩展的ifelse语句

 1 if(判断条件1){
 2   执行语句1
 3 }else if(判断语句2){
 4   执行语句2
 5 }
 6 ...
 7 }else if(判断语句n){
 8   执行语句n
 9 }else{
10   执行语句n+1
11 }

  执行流程:

    可以理解成多个if else,哪一个判断语句是true就执行那个,否则执行最后一else。  

  执行流程图:

   多者选其一:

 1 public class Ifelseplus{
 2     public static void main(String[] args){
 3     int x = 5;
 4     int y;
 5 
 6     if (x < 0){
 7       y = -x;
 8     }else if(x = 0){
 9       y = 10;
10     }else{
11       y = 10*x;
12     }
13   }
14 }

  

猜你喜欢

转载自www.cnblogs.com/koss/p/12274433.html