• If选择结构


    格式1:

    if(关系表达式){

      语句体;

    }

    执行流程:

    1、首先计算表达式的值

    2、判断表达式的值如果为true将就执行语句体,如果为false不执行语句体

    3、继续执行后面的语句内容

    注意事项:

    1、如果if语句所控制的语句体是一条语句,大括号可以不用写,但是不建议。

    2、if语句的小括号后面不用写分号

     1 package day03;
     2 
     3 public class IfDemo01 {
     4     public static void main(String[] args) {
     5         System.out.println("开始");
     6         int age = 17;
     7         if (age >= 12) {
     8             System.out.println("可以玩平板电脑");
     9         }
    10         System.out.println("结束");
    11     }
    12 }

    执行结果:

     格式2:

    if(关系表达式){

      语句体1;

    }

    else{

      语句体2;

    }

    执行流程:

    1、首先计算关系表达式的值

    2、判断关系表达式的值为true执行语句体1,如果为false执行语句体2

    3、继续执行后面的语句内容

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

    执行结果:

     格式3:

    if (判断条件1) {
      语句体1;
    }

    else if (判断条件2) {
      语句体2;
    }

    else {
      语句体n+1;
    }

    执行流程:

    1、首先计算判断条件1的值

    2、如果值为true就执行语句体1,如果为false就计算条件2的值并进行判断

    3、如果值为true就执行语句体2,如果为false就计算判断条件3的值

    ……

    如果没有任何判断条件为true就执行语句体n+1

    eg:

     1 package day03;
     2 
     3 public class IfDemo03 {
     4     public static void main(String[] args) {
     5         int score = 90;
     6         if (score>= 90 &&score<=100){
     7             System.out.println("优秀");
     8         }
     9         else if (score>=80&score<=89){
    10             System.out.println("良好");
    11         }
    12         else if (score>=70&score<=79){
    13             System.out.println("中等");
    14         }
    15         else if (score>=60&score<=69){
    16             System.out.println("及格");
    17         }
    18         else if (score>=0&score<=59){
    19             System.out.println("不及格,请加油!");
    20         }
    21         else {
    22             System.out.println("数据有误");
    23         }
    24     }
    25 }

    执行结果:

    欢迎批评指正,提出问题,谢谢!
  • 相关阅读:
    Higher-Order Functions and Lambdas
    dispatch_sync:As an optimization, this function invokes the block on the current thread when possible
    为什么使用dispatch_sync
    如何安全使用dispatch_sync
    dispatch_sync
    Dispatch Queues and Thread Safety
    高阶函数-参数与返回值
    In Swift, typedef is called typealias:
    偏函数应用(Partial Application)和函数柯里化(Currying)
    Centos下添加用户到用户组
  • 原文地址:https://www.cnblogs.com/xxeleanor/p/14195093.html
Copyright © 2020-2023  润新知