判断语句之if..else if...else

时间:2023-03-09 05:03:32
判断语句之if..else if...else

判断语句之if..else if...else

  • if语句第三种格式:if..else if...else

格式:

判断语句之if..else if...else

执行流程

首先判断关系表达式1看其结果是true还是false

如果是true就执行语句体1

如果是false就继续判断关系表达式2看其结果是true还是false

如果是true就执行语句体2

如果是false就继续判断关系表达式…看其结果是true还是false

如果没有任何关系表达式为true,就执行语句体n+1。

代码举例:

public class Demo04IfElseExt {
    public static void main(String[] args) {
        /*x和y的关系满足如下:
         x>=3 y = 2x + 1;
        ‐1<=x<3 y = 2x;
        x<=‐1 y = 2x – 1;
       根据给定的x的值,计算出y的值并输出。
         */
        int x = 15;
        int y;
        if (x >= 3) {
            y = 2 * x + 1;
        } else if (x >= -1 && x < 3) {
            y = 2 * x;
        } else {
            y = 2 * x - 1;
        }
        System.out.println("y的值是:" + y);
    }

}

执行结果:

判断语句之if..else if...else

if..else if...else执行流程如下图所示:

判断语句之if..else if...else