JAVA Switch-case instance and usage

There is something similar to if-else in Java, that is switch-case.

It has the following rules:

  • The variable type in the switch statement can be: byte, short, int or char. Starting from Java SE 7, switch supports the String type, and the case label must be a string constant or literal.
  • A switch statement can have multiple case statements. Each case is followed by a value to compare and a colon.
  • The data type of the value in the case statement must be the same as the data type of the variable, and it can only be a constant or a literal constant.
  • When the value of the variable is equal to the value of the case statement, then the statement after the case statement will be executed, and the switch statement will not be jumped out until the break statement appears.
  • A switch statement terminates when a break statement is encountered. The program jumps to the statement following the switch statement. A case statement does not have to contain a break statement. If no break statement appears, the program will continue to execute the next case statement until a break statement appears.
  • A switch statement can contain a default branch, which is usually the last branch of the switch statement (it can be anywhere, but is usually the last). default is executed when there is no case statement whose value is equal to the variable value. The default branch does not require a break statement. (If there is no break statement in the case statement, the program will be executed until the default branch)


Original link: https://blog.csdn.net/weixin_42352733/article/details/122536482

The syntax format of switch:

switch (表达式) {
    case 常量表达式或枚举常量:
        语句;
        break;
    case 常量表达式或枚举常量:
        语句;
        break;
        ......
    default: 语句;
        break;
}

 Here is an example:

According to the student's achievement level, judge the student's achievement range. We stipulate that  A grades represent  90~100 points, B grades represent  80~89 points, C grades represent  70~79 points, D grades represent  60~69 points, E and grades represent  0~59 points. If it is  A~E a letter other than that, use  Unknown level .

public class Solution {
    public String getRange(String level) {
        String str="";
        // write your code here
        switch(level){
            case "A":
                str = "90~100";
                break;
            case "B":
                str = "80~89";
                break;
            case "C":
                str = "70~79";
                break;
            case "D":
                str = "60~69";
                break;
            case "E":
                str = "0~59";
                break;
            default:
                str = "Unknown level";
                break;
        }
        return str;
    }
}

 This is the basic usage of Switch-case statement in Java

Guess you like

Origin blog.csdn.net/Harvery_/article/details/126323071