Using switch Structures
Submitted by GeePee on Wednesday, May 20, 2015 - 21:42.
The following is a Java Program using switch structures. In Java, switch, case, break and default are reserved words. In a switch structure, the expression is evaluated first. The value of expression is then used to perform the actions specified in the statements that follow the reserved word case. I will be using the JCreator IDE in developing the program.
To start in this tutorial, first open the JCreator IDE, click new and paste the following code:
- import java.util.*;
- public class BreakStatementInSwitch
- {
- {
- int num;
- num = console.nextInt();
- switch (num)
- {
- case 0:
- break;
- case 6:
- case 7:
- break;
- case 9: break;
- break;
- }
- }
- }
Sample Run 1:
Enter an integer between 0 and 10:
1
The number you enter is 1
Hello there I am Dodgers
Out of the switch structure!
Sample run 2:
Enter an integer between 0 and 10:
3
The number you enter is 3
I am Dodgers
Out of the switch structure!
Sample run 3:
Enter an integer between 0 and 10:
4
The number you enter is 4
Dodgers
Out of the switch structure!
Sample run 4:
Enter an integer between 0 and 10:
5
The number you enter is 5
How are you Out of the switch structure!
Sample run 5:
Enter an integer between 0 and 10:
7
The number you enter is 7
are you Out of the switch structure!
Sample run 6:
Enter an integer between 0 and 10:
9
The number you enter is 9
Out of the switch structure!
Sample run 7:
Enter an integer between 0 and 10:
10
The number you enter is 10
Have a nice day!
Out of the switch structure!
Sample run 8:
Enter an integer between 0 and 10:
11
The number you enter is 11
Sorry the number is out of range!
Out of the switch structure!
A walk through of this program, using certain values of the switch expression, num
, can help you understand how the break
statement functions.
If the value of num = 0
, the value of the switch expression matches the case value .
The first break appears break;
, just before the case value of 5.
When the value of the switch statement expression matches a case value, all statements execute until a break is encountered, and the program skips all case labels in between.
If the value of num is 3, it matches the case value of 3 and the statements following this label execute until the break statement is encountered in break;
.
If the value of num is 9, it matches the case value of 9.
In this situation, the action is empty, because only break statement case 9: break;
, follows the case value of 9.
Add new comment
- 77 views