Computer Science, asked by binujoel800, 2 months ago

13. Convert the following if-elseif construct into switch -case:
If (var==1)
System.out.println("Jan");
Else if (var==2)
System.out.println(“Feb");
Else if (var==3)
System.out.println("March");
Else if
System.out.println("Invalid”);​

Attachments:

Answers

Answered by kamalrajatjoshi94
0

Answer:

Note:The last statement must be else not else if there may be a misprint and also 'else ' is written in lowercase not uppercase ok.

Conversion from if-else to switch case:-

switch(var)

{

case 1:

System.out.println("Jan");

break;

case 2:

System.out.println("Feb");

break;

case 3:

System.out.println("March");

break;

default:

System.out.println("Invalid");

}

Concept:-

  • While converting if-else to switch case first look at the control variable I.e in if else the variable which is used multiple times here it is var now use switch(control variable).
  • Now look at the type of variable used if the variable is int there leave it like that if a char variable is used close it under single quotes like case 'A': Note after case <type of variable> a colon must be applied and at the end of each statements use a break statement.
  • In the last see where is the else and use the default case there.

Answered by BrainlyProgrammer
2

Given Snippet(after correction:-

if (var==1)

System.out.println("Jan");

else if (var==2)

System.out.println(“Feb");

else if (var==3)

System.out.println("March");

else

System.out.println("Invalid”);

Answer:-

switch(var){

case 1: System.out.println("Jan");break;

case 2: System.out.println("Feb"); break;

case 3: System.out.println("Mar"); break;

default: System.out.println("Invalid"); break;

}

Similar questions