Write a program to print month number by reading month name using switch case in java?
Answers
The given problem is solved using language - Java.
import java.util.Scanner;
public class Brainly{
public static void main(String s[]){
Scanner sc=new Scanner(System.in);
System.out.print("Enter month name (full name): ");
String name=sc.next().toUpperCase();
sc.close();
switch(name){
case "JANUARY":
System.out.println("Month Number: 1");
break;
case "FEBRUARY":
System.out.println("Month Number: 2");
break;
case "MARCH":
System.out.println("Month Number: 3");
break;
case "APRIL":
System.out.println("Month Number: 4");
break;
case "MAY":
System.out.println("Month Number: 5");
break;
case "JUNE":
System.out.println("Month Number: 6");
break;
case "JULY":
System.out.println("Month Number: 7");
break;
case "AUGUST":
System.out.println("Month Number: 8");
break;
case "SEPTEMBER":
System.out.println("Month Number: 9");
break;
case "OCTOBER":
System.out.println("Month Number: 10");
break;
case "NOVEMBER":
System.out.println("Month Number: 11");
break;
case "DECEMBER":
System.out.println("Month Number: 12");
break;
default: System.out.println("Invalid Data.");
}
}
}
- At first, we have asked the user to enter the month. The entered month is stored in a variable after converting it into uppercase.
- Using switch case construct, the month number is calculated and it is displayed on the screen.
- For an invalid input, an appropriate message is displayed on the screen.
See the attachment for output.
Answer:
import java.util.Scanner;
public class Brainly{
public static void main(String s[]){
Scanner sc=new Scanner(System.in);
System.out.print("Enter month name (full name): ");
String name=sc.next().toUpperCase();
sc.close();
switch(name){
case "JANUARY":
System.out.println("Month Number: 1");
break;
case "FEBRUARY":
System.out.println("Month Number: 2");
break;
case "MARCH":
System.out.println("Month Number: 3");
break;
case "APRIL":
System.out.println("Month Number: 4");
break;
case "MAY":
System.out.println("Month Number: 5");
break;
case "JUNE":
System.out.println("Month Number: 6");
break;
case "JULY":
System.out.println("Month Number: 7");
break;
case "AUGUST":
System.out.println("Month Number: 8");
break;
case "SEPTEMBER":
System.out.println("Month Number: 9");
break;
case "OCTOBER":
System.out.println("Month Number: 10");
break;
case "NOVEMBER":
System.out.println("Month Number: 11");
break;
case "DECEMBER":
System.out.println("Month Number: 12");
break;
default: System.out.println("Invalid Data.");
}
}
}