write a program in Java to display name of month of the year using switch case
please help me
Answers
Explanation:
import java.util.Scanner;class switch{ public static void main(String[] args){ int season =0; Scanner sc =new Scanner (System.in); System.out.println(); ...
Answer:
Switch statement
Switch statement helps simplifying multiple choices in a program. Let's start with the sample problem.
Problem. User enters month's number, then program tells month's name.
If-based solution
First, let's solve it using if statement.
import java.util.Scanner;
public class IfBasedSolution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter month's number: ");
int monthNumber;
monthNumber = in.nextInt();
if (monthNumber == 1)
System.out.println("January");
else if (monthNumber == 2)
System.out.println("February");
else if (monthNumber == 3)
System.out.println("March");
else if (monthNumber == 4)
System.out.println("April");
else if (monthNumber == 5)
System.out.println("May");
else if (monthNumber == 6)
System.out.println("June");
else if (monthNumber == 7)
System.out.println("July");
else if (monthNumber == 8)
System.out.println("August");
else if (monthNumber == 9)
System.out.println("September");
else if (monthNumber == 10)
System.out.println("October");
else if (monthNumber == 11)
System.out.println("November");
else if (monthNumber == 12)
System.out.println("December");
else
System.out.println("Invalid month.");
}
}
Enter month's number: 5
May
One can see excessive code repetition: all lines with if are almost the same, except for one number. From the viewpoint of coding style it's not good at all.