Syntax of switch structure (switch statement)
switch(expression){--->Type is int, char case constant 1 :--->case structure can have multiple // statement block 1break;--->Program breaks out of switch structure case constant n :--->The values of constants cannot be the same // statement block nbreak;default:--->The role of else in if structure is the same // statement block break;}Let’s see a code example below, with detailed comments, you can refer to:
public class SwitchStu{/* switch: switch(variable){ case literal A: code A; break; case literal B: code B; break; default: code E } Code C judges the value of the variable. If the value is equal to A, name executes A, if equal to B, name executes B. If all case conditions are not met, then the code to execute default is underwritten: After the condition of a case is met, before encountering break, all the code after the next case will be executed Note: 1. There cannot be duplicate labels (values) in the case 2. When there is no statement after the case, you can write nothing or write one; 3. Switch can only judge the int type (and types that can be automatically converted to int), and after jdk1.7, you can judge the string and enum type expansion: If block, the brackets of branches like switch can be omitted, but it is not recommended to reduce the readability of the code (when the branch has only one sentence of code) */public static void main(String[] args){java.util.Scanner sc = new java.util.Scanner(System.in);System.out.println("Please enter your age");char age = (char)sc.nextint();// char ch = 'I';// int i = ch;String str = "6";switch(str){case "16": case "17": case "18":System.out.println("Study in high school");break;case "12":System.out.println("Study in grade 6");break;case "6":System.out.println("Study in grade 1");break;default:System.out.println("Not studying anymore");}System.out.println("Go home, be scolded");if(age%2==0) System.out.println("is an even number");System.out.println("Code continues to be textured");}}Summarize
The above is all the detailed explanation of the switch selection statement code in Java. I hope it will be helpful to everyone. Interested friends can continue to refer to this site:
Java performs instance analysis of Object from the perspective of JDK source code
Detailed explanation of Java internal test class code
Inheritance test code analysis in java
If there are any shortcomings, please point them out. Thank you friends for your support for this site!