美文网首页
4. Java流程控制

4. Java流程控制

作者: 轻轻敲醒沉睡的心灵 | 来源:发表于2024-08-16 09:22 被阅读0次

    1. if判断

    • 1.1 基本语法:
    if (条件) {
        // 条件满足时执行
    }
    if (n >= 60) {
        System.out.println("及格了");
    }
    

    当if语句块只有一行语句时,可以省略花括号{},但不建议这么做,容易出错

    • 1.2 else
      if语句还可以编写一个else { ... },当条件判断为false时,将执行else的语句块:
    public class Main {
        public static void main(String[] args) {
            int n = 70;
            if (n >= 60) {
                System.out.println("及格了");
            } else {
                System.out.println("挂科了");
            }
        }
    }
    
    • 1.3 else if 串联
    public class Main {
        public static void main(String[] args) {
            int n = 70;
            if (n >= 90) {
                System.out.println("优秀");
            } else if (n >= 80) {
                System.out.println("可以");
            } else if (n >= 60) {
                System.out.println("及格了");
            } else {
                System.out.println("挂科了");
            }
        }
    }
    

    2. switch多重选择

    switch语句根据switch (表达式)计算的结果,跳转到匹配的case结果(匹配不到,走default),然后继续执行后续语句,直到遇到break结束执行。

    // 正确格式,每个里面都有break
    public class Main {
        public static void main(String[] args) {
            int option = 99;
            switch (option) {
            case 1:
                System.out.println("Selected 1");
                break;
            case 2:
                System.out.println("Selected 2");
                break;
            case 3:
                System.out.println("Selected 3");
                break;
            default:
                System.out.println("Not selected");
                break;
            }
        }
    }
    

    当缺少break时,逻辑可能出错

    public class Main {
        public static void main(String[] args) {
            int option = 1;
            switch (option) {
            case 1:
                System.out.println("Selected 1");
            case 2:
                System.out.println("Selected 2");
                break;
            case 3:
                System.out.println("Selected 3");
                break;
            }
        }
    }
    // 此时会输出  Selected 1      Selected 2,因为1中无break,2中才有,进入以后会一直执行,直到遇见break(或者结尾)
    

    相关文章

      网友评论

          本文标题:4. Java流程控制

          本文链接:https://www.haomeiwen.com/subject/jxpvqltx.html