The format is as follows:
When the value of an expression is equal to the value of a case statement, all statements underneath it are run until a break is encountered. If the value of any case statement is not equal to the value of the expression, the statement under optional label default is run.
(a) in the JDK version after Java 1.7, the type of the expression in the switch in Java can be of type string. (The JDK version must be 1.7, 1.5 may only be int or char type!)
The code is as follows:
Package test0428;
Import Java.io.File;
Import Java.util.Scanner;
/*
* Java.io.file representation file (directory)
* The file class is only for directory access and cannot be used for file content access
* */
public class Testfile {
Understanding constructors, alt+/view Help
public static void Main (string[] agrs) {
SYSTEM.OUT.PRINTLN ("Please choose");
String Str=in.next ();
Switch (str) {
Case "ABC":
SYSTEM.OUT.PRINTLN ("abc");
Break
Case "BCD":
System.out.println ("BCD");
Break
Default:
SYSTEM.OUT.PRINTLN ("Default");
Break
}
}
}
The results of the operation are as follows:
Please select
Abc
Abc
(b) The expression in the switch cannot be a Boolean type. If you want to convert to a Boolean type, you can only convert to a string and then use the following code:
Boolean flag1=true;
Switch (flag1+ "") {
Case "true":
System.out.println ("Boolean: true");
Break
Case "Flase":
System.out.println ("Boolean type: Flase");
Break
Default:
SYSTEM.OUT.PRINTLN ("Default");
Break
}