The first question: When to use switch ' multi-branch, you can use a switch case when you need to use multiple if else
Case Planet score score, supports horizontal classification, vertical treatment
public static void Main (string[] args) {
Scanner s = new Scanner (system.in);
System.out.println ("Please enter Student Planet:");
String star = S.nextline ();
System.out.println ("Please enter student score:");
String score = S.nextline ();
int SCO = integer.valueof (score). Intvalue ();
Switch (Star) {
Case "Earth":
if (Sco > 90) {
System.out.println ("FA 1000 Scholarship");
} else {
System.out.println ("FA 800 Scholarship");
}
;
Break
Case "Moon":
if (Sco > 90) {
System.out.println ("10 pounds of Moon cakes");
} else {
System.out.println ("8 pounds of Moon cakes");
}
Break
Case "Jupiter":
if (Sco > 90) {
System.out.println ("10 Pounds of diamonds");
} else {
System.out.println ("8 pounds of diamonds");
}
The second problem, in case of defining variables, is to add {} after the colon
If you want to define a variable in a case:
Switch (Formway)
{
Case 1:
int a=2; Error. Because of the ambiguous scope of the case, the compiler cannot define a variable here.
...
Case 2:
...
}
In this case, add {} To resolve the issue.
Switch (Formway)
{
Case 1:
{
int a=2; Correctly, variable A is explicitly scoped to the current {} range.
...
}
Case 2:
...
}
public static void Main (string[] args) {
Scanner s = new Scanner (system.in);
System.out.println ("Please enter Student Province:");
String province = S.nextline ();
Switch (province) {
Case "Hebei": {
int a = 13;
SYSTEM.OUT.PRINTLN ("Define variables in case to add {}" + a);
}
;
Break
Case "Shandong":
{
char c = ' x ';
SYSTEM.OUT.PRINTLN ("Define variables in case to add {}" + C);
};break;
Case "Hunan":
{
Short B = 100;
SYSTEM.OUT.PRINTLN ("Define variables in case to add {}" +b);
};
Break
Case "Guangzhou":
{
Date d = new Date ();
SYSTEM.OUT.PRINTLN ("Define variables in case to add {}" +d);
}
Break
Default:
{
Pelpel p = new Pelpel ();
P.setage (20);
P.setsex (1);
SYSTEM.OUT.PRINTLN ("Case definition variable to be added {}\t Age:" + p.getage () + "\ T Gender:" +p.getsex ());
}
When does switch case work?