知识库 知识库
首页
  • Hyperskill - Java

    • Java basic
    • Java OOP
    • 应知
    • 扩展
    • IO & Stream
    • Error & Exception
    • Algorithm & Data structure
    • Design pattern
    • Web
    • Spring boot
  • 练习题

    • 选择题 & 填空题
    • 代码题
  • Frank - Java与生活 (OOP)

    • 参考资料
    • Java基础
    • OOP上半部分
    • OOP下半部分
  • Frank - Java API进阶

    • Base API
    • Unit Test and main function
  • 学习笔记
  • 学习笔记

    • 数据库
  • Frank - MySQL删库跑路

    • 安装、连接、配置
    • 基本操作——数据库
    • 基本操作——表
    • 基本操作——数据
    • 数据类型
    • 列属性完整性
    • 数据库设计思维
    • 单表查询
    • 多表查询
  • 学习笔记

    • 其它
  • Frank - Linux现代方法

    • 必知
    • 命令
    • 技巧
  • 技术文档
  • Git
  • GitHub技巧
  • 前端
  • Khan Academy - 语法
  • Monthly
  • 阅读
  • Others
  • 学习
  • 面试
  • 心情杂货
  • 实用技巧
  • 友情链接
收藏
  • 标签
  • 归档
GitHub (opens new window)

Jim FuckPPT

Java小学生
首页
  • Hyperskill - Java

    • Java basic
    • Java OOP
    • 应知
    • 扩展
    • IO & Stream
    • Error & Exception
    • Algorithm & Data structure
    • Design pattern
    • Web
    • Spring boot
  • 练习题

    • 选择题 & 填空题
    • 代码题
  • Frank - Java与生活 (OOP)

    • 参考资料
    • Java基础
    • OOP上半部分
    • OOP下半部分
  • Frank - Java API进阶

    • Base API
    • Unit Test and main function
  • 学习笔记
  • 学习笔记

    • 数据库
  • Frank - MySQL删库跑路

    • 安装、连接、配置
    • 基本操作——数据库
    • 基本操作——表
    • 基本操作——数据
    • 数据类型
    • 列属性完整性
    • 数据库设计思维
    • 单表查询
    • 多表查询
  • 学习笔记

    • 其它
  • Frank - Linux现代方法

    • 必知
    • 命令
    • 技巧
  • 技术文档
  • Git
  • GitHub技巧
  • 前端
  • Khan Academy - 语法
  • Monthly
  • 阅读
  • Others
  • 学习
  • 面试
  • 心情杂货
  • 实用技巧
  • 友情链接
收藏
  • 标签
  • 归档
GitHub (opens new window)
  • Hyperskill - Java

    • Java basic

      • Theory:Scanning the input
      • Theory:Arithmetic operations
      • Theory:Integer types and operations
      • Theory:Increment and decrement
      • Theory:Relational operators
      • Theory:Ternary operator
      • Theory:The while and do-while loops
      • Theory:Branching statements
      • Theory:Characters
      • Theory:String
      • Theory:Boolean and logical operators
      • Theory:Sizes and ranges
      • Theory:Switch statement
        • When a conditional statement is not so good
        • Three keywords: switch, case, and default
        • The general form of the switch statement
        • An example with "zero", "one" and "two"
        • Conclusion
      • Theory:Declaring a method
      • Theory:The main method
      • Theory:Type casting
      • Theory:Primitive and reference types
      • Theory:Array
      • Theory:Arrays as parameters
      • Theory:Iterating over arrays
      • Theory:Multidimensional array
      • Theory:Final variables
    • Java OOP

    • 应知

    • 扩展

    • IO & Stream

    • Error & Exception

    • Algorithm & Data structure

    • Design pattern

    • Web

    • Spring boot

  • 练习题

  • Frank - Java与生活

  • Frank - Java API进阶

  • 学习笔记

  • Java
  • Hyperskill - Java
  • Java basic
Jim
2022-08-09
目录

Theory:Switch statement

  • # When a conditional statement is not so good

    Suppose you need to write a program that performs different actions depending on the value of a variable. For example, choosing an action from the menu of a game. To do that you can use a conditional statement with multiple branches as shown below.

    int action = ...; // a certain value from 1 to 4
            
    if (action == 1) {
        System.out.println("Starting a new game...");
    } else if (action == 2) {
        System.out.println("Loading a saved game");
    } else if (action == 3) {
        System.out.println("Displaying help...");
    } else if (action == 4) {
        System.out.println("Exiting...");
    } else {
        System.out.println("Unsuitable action, please, try again");
    }
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13

    Of course, this code handles the task. But if your conditional statement has a lot of branches, it can be hard to understand for people.

    # Three keywords: switch, case, and default

    The switch statement provides a way to choose between multiple cases based on the value of a single variable (not an expression!). The variable can be an integer number, character, string, or enumeration. The last two types will be studied further.

    Using the switch statement, the previous code will look like this:

    switch (action) {
        case 1:
            System.out.println("Starting a new game...");
            break;
        case 2:
            System.out.println("Loading a saved game");
            break;
        case 3:
            System.out.println("Displaying help...");
            break;
        case 4:
            System.out.println("Exiting...");
            break;
        default:
            System.out.println("Unsuitable action, please, try again");
    }
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16

    As you can see, this code is well-structured and easier to read than the equal conditional statement. We have not explained the keywords switch, case and break yet, but you can already guess what they mean.

    # The general form of the switch statement

    The most general form of the switch statement is the following

    switch (variable) {
        case value1:
            // do something here
            break;
        case value2:
            // do something here
            break;
        
        //... other cases
        
        case valueN:
            // do something here
            break;
        default:
            // do something by default
            break; // it can be omitted
    }
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17

    The switch and case keywords are always required here. The keywords break and default are optional. The keyword breakstops the execution of the whole switch statement, not just one case.

    If a case does not have the break keyword, the following case will be evaluated as well, including the default case. The default case is also evaluated if there's no other case that matches the variable value. The break keyword in the default branch is optional and can be omitted.

    A case section may contain any block of code, even a nested switch statement, however it is recommended to avoid deeply nested code structures wherever possible.

    # An example with "zero", "one" and "two"

    Let's consider another example. The following code outputs the names of integer numbers or a default text. This switch statement has three base cases and a single default case.

    int val = ...;
    switch (val) {
         case 0:
             System.out.println("zero");
             break;
         case 1:
             System.out.println("one");
             break;
         case 2:
             System.out.println("two");
             break;
         default:
             System.out.println("The value is less than zero or greater than two");
    } 
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14

    If the val is 0, the code prints:

    zero
    
    1

    If the val is 1, the code prints:

    one
    
    1

    if the val is 10, the code prints:

    The value is less than zero or greater than two
    
    1

    If you forget the keyword break in a case, the compiler won't consider it an error. Let's remove it from the second case (case 1) and assign 1 to val. The program prints:

    one
    two
    
    1
    2

    Omitting break keyword is not a good practice. Try to avoid it.

    Java 12–14 introduced some new features allowing to use switch as an expression (opens new window).

    # Conclusion

    When you have a limited number of cases to choose from, switch statements can help you avoid unnecessary nested if-else constructions. For that, you need the switch keyword to introduce the value to evaluate, and case for each of the possible values. Do not forget to also use the break keyword to avoid evaluating extra cases and default branch to indicate the default behavior.

编辑 (opens new window)
#Java basic
上次更新: 2022/09/26, 16:55:15
Theory:Sizes and ranges
Theory:Declaring a method

← Theory:Sizes and ranges Theory:Declaring a method→

最近更新
01
《挪威的森林》
04-14
02
青钢影
04-14
03
Processing strings
02-18
更多文章>
Theme by Vdoing | Copyright © 2022-2023 Jim Frank | MIT License
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式