A common problem in programming is to detect whether a variable conforms to a condition, and switch implements a "Multiple choice" option in a straightforward way, with the following syntax:
/*switch evaluates the expression first, and executes several statements after the case statement until a break is encountered if the value of the expression is the same as the value of the variable that follows it. At this point, if there is no break statement in the case statement, the following statements continue to be executed until a break statement is encountered. If no value of a constant is the same as the value of the expression, the statement following the default is executed. The default statement is optional, and if it does not exist, and the value of the expression in the switch statement is not the same as the constant value of any case, switch does nothing. */Switch(expression) { CaseConstant value 1://constant value must be integer or character typeStatement 1; [ Break;] Caseconstant Value 2: statement 2; [ Break;] .... Caseconstant Value N: statement n; [ Break;]default: statement n+1; [ Break;]}
Example: The output of English values from Monday to Wednesday
Public Static voidMain (string[] args) {intweek=2;//define INT type variable week Switch(week) {//the expression that defines the switch statement is a variable week Case1://The constant that defines the case statement is 1System.out.println ("Monday");//Output Results Break;//End Case2: System.out.println ("Tuesday"); Break; Case3: System.out.println ("Wednesday"); Break; default://Default StatementSystem.out.println ("Sorry,i don ' t know"); } }
A brief analysis of switch multi-branch statement