Switch is one of the conditional statements which is useful in selecting one among in multiple options.
Syntax:
Switch(Option)
{
Case 1: statements…..
break;
Case 2: statements…..
break;
---------------------------
---------------------------
Case n: statements…..
break;
}
Example for switch conditional statement is given below.
Java Program to print the month using switch case:
- · Create a class SwitchMonth with main() function.
- · Get the input from user. Using the switch statement,pass the input.
- · Based on the input given, case statement is selected.
- · The output is displayed as per the input.
//Java Program to print the month using switch case:
import java.util.Scanner;
public class SwitchMonth {
public static void
main(String[] args) {
Scanner scanner =
new Scanner(System.in);
System.out.print("Enter the number of the month:");
int m=
scanner.nextInt();
switch (m) {
case 1:
System.out.println("January");
break;
case 2:
System.out.println("February");
break;
case 3:
System.out.println("March");
break;
case 4:
System.out.println("April");
break;
case 5:
System.out.println("May");
break;
case 6:
System.out.println("June");
break;
case 7:
System.out.println("July");
break;
case 8:
System.out.println("August");
break;
case 9:
System.out.println("September");
break;
case 10:
System.out.println("October");
break;
case 11:
System.out.println("November");
break;
case 12:
System.out.println("December");
break;
default:
System.out.println("Invalid Month");
break;
}
}
}
·
Compile and execute the program as follows…
C:\raji\blog>javac SwitchMonth.java
C:\raji\blog>java SwitchMonth
Enter the number of the month:6
June
C:\raji\blog>java SwitchMonth
Enter the number of the month:11
November
C:\raji\blog>java SwitchMonth
Enter the number of the month:3
March
C:\raji\blog>java SwitchMonth
Enter the number of the month:20
Invalid Month
This is the way of implementing switch statements to display
the month name according to the user’s choice.
No comments:
Post a Comment