In: Computer Science
Convert the following switch statement into if-else statements:
int month = input.nextInt();
switch (month) {
case 1: System.out.println(“January”);
case 2: System.out.println(“February”); break;
case 3: System.out.println(“March”); break;
case 4: System.out.println(“April”);
case 5: System.out.println(“May”); break;
default: System.out.println(“Invalid”); break;
}
example:
if (month == 1) {
System.out.println("January");
System.out.println("February"); }
if (month == 2)
{ System.out.println("February");
}
}
}
Please continue the code! Thanks
int month = input.nextInt();
switch (month) {
case 1: System.out.println(“January”);
case 2: System.out.println(“February”); break;
case 3: System.out.println(“March”); break;
case 4: System.out.println(“April”);
case 5: System.out.println(“May”); break;
default: System.out.println(“Invalid”); break;
}
The Above Switch statement has been converted into if-else statements i.e the else- if statements.
import java.util.*;
public class Months
{
public static void main(String[] args)
{
Scanner input=new Scanner(System.in);
System.out.println("Enter the month in terms of number");
int month=input.nextInt();//Getting input from user
if(month==1)//if the condition is true,the statements inside the if statemnent gets executed.
{
System.out.println("January");
System.out.println("February");
}
else if(month==2)
{
System.out.println("February");
}
else if(month==3)
{
System.out.println("March");
}
else if(month==4)
{
System.out.println("April");
System.out.println("May");
}
else if(month==5)
{
System.out.println("May");
}
else //if none of the conditions are true,then else statement gets executed.
{
System.out.println("Invalid");
}
}
}
Screenshot of the program with the output is given below :

Output is March,if the user inputs the value as 3,the output will be displayed as March.