Sie sind auf Seite 1von 4

The syntax of a switch case statement is the following:

switch (variable) {
case c1:
statements // they are executed if variable == c1
break;
case c2:
statements // they are executed if variable == c2
break;
case c3:
case c4:
statements // they are executed if variable == any of the above c's
break;
...
default:
statements // they are executed if none of the above case is satisfied
break;
}
. Example of switch case

03 public class SwitchCaseExample {


04 public static void main(String[] args) {
05
06
grading('A');
07
grading('C');
08
grading('E');
09
grading('G');
10 }
11
12 public static void grading(char grade) {
13
14
int success;
15
switch (grade) {
16
case 'A':
17
System.out.println("Excellent grade");
18
success = 1;
19
break;
20
case 'B':
21
System.out.println("Very good grade");

22
success = 1;
23
break;
24
case 'C':
25
System.out.println("Good grade");
26
success = 1;
27
break;
28
case 'D':
29
case 'E':
30
case 'F':
31
System.out.println("Low grade");
32
success = 0;
33
break;
34
default:
35
System.out.println("Invalid grade");
36
success = -1;
37
break;
38
}
39
40
passTheCourse(success);
41
42 }
43
44 public static void passTheCourse(int success) {
45
switch (success) {
46
case -1:
47
System.out.println("No result");
48
break;
49
case 0:
50
System.out.println("Final result: Fail");
51
break;
52
case 1:
53
System.out.println("Final result: Success");
54
break;
55
default:
56
System.out.println("Unknown result");
57
break;
58
}
59
60 }
61
62 }
In the above code we can see two switch case statements, one using char as data
type of the expression of the switch keyword and one using int .

Output:
Excellent grade

Final result: Success


Good grade
Final result: Success
Low grade
Final result: Fail
Invalid grade
No result
Below is the equivalent of the switch case statement in the
method passTheCourse() using if..then..else :
1 if (success == -1) {
2
System.out.println("No result");
3 } else if (success == 0) {
4 System.out.println("Final result: Fail");
5 } else if (success == 1) {
6 System.out.println("Final result: Success");
7 } else {
8 System.out.println("Unknown result");
9}

Example of switch case using String


03 public class StringSwitchCase {
04
12
public static void main (String [] arg)
13
{
14
switch(island) {
15
case "Corfu":
16
System.out.println("User wants to visit Corfu");
17
break;

18
case "Crete":
19
System.out.println("User wants to visit Crete");
20
break;
21
case "Santorini":
22
System.out.println("User wants to visit Santorini");
23
break;
24
case "Mykonos":
25
System.out.println("User wants to visit Mykonos");
26
break;
27
default:
28
System.out.println("Unknown Island");
29
break;
30
}
31 }
32
33 }
If we run the above code, we will have the following result:

Output:
User wants to visit Santorini
User wants to visit Crete
Unknown Island

Das könnte Ihnen auch gefallen