To understand the switch statement, let's consider a problem. We will first solve this problem by using if and then we will solve this problem by using switch statement. Let us consider a program that will input a number from 1-7 and then display the day of week that corresponds to the number. The correspondence is as follows:
1. Monday
2. Teuesday
3. Wednesday
4. Thursday
5. Friday
6. Saturday
7. Sunday
Solution for this problem by using if
Now let's see the syntax for switch statement:
switch (variable) { case value1 : /*This will be executed if the value of variable is equal to the value1*/ break; case value2 : /*This will be executed if the value of variable is equal to value2*/ default : /*This will be executed if the value of variable is not equal to any of the above values*/ }
*You can use as many case statements as you want
**It is not necessary to add the default statement
***If you do not add the break; statement, all the below statements will also be executed
Now let's solve the above problem using switch:
package lesson.pkg13; import java.util.Scanner; public class Lesson13 { public static void main(String[] args) { Scanner in = new Scanner(System.in); int i=in.nextInt(); switch (i) { case 1: System.out.println("Monday"); break; case 2: System.out.println("Tuesday"); break; case 3: System.out.println("Wednesday"); break; case 4: System.out.println("Thursday"); break; case 5: System.out.println("Friday"); break; case 6: System.out.println("Saturday"); break; case 7: System.out.println("Sunday"); break; default : System.out.println("Wromg input"); } } }
*Try to remove break; to see what happens
Practice Corner:
- Write a program to input the month number and display the name of the month on the screen.
0 Comments
Thanks for leaving a comment. I will try to reply you soon.