将以下的 switch 语句转换为 if-else 语句:

huangapple go评论79阅读模式
英文:

Convert the following switch statement into if-else statements:

问题

int month = input.nextInt();
if (month == 1) {
    System.out.println("January");
}
else if (month == 2) {
    System.out.println("February");
}
else if (month == 3) {
    System.out.println("March");
}
else if (month == 4) {
    System.out.println("April");
}
else if (month == 5) {
    System.out.println("May");
}
else {
    System.out.println("Invalid");
}
英文:
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;
}

How do I convert it from switch statement into if-else statment?

the breaks are intentional, this is a college assignment.

答案1

得分: 1

在伪代码中,您可以在单个语句中检查所有连接的部分,而不使用 break 语句,并在另一个嵌套的 if 语句中检查值。

如果 1 或 2
    如果 1 则打印一月
    打印二月
否则如果 3 则打印三月
否则如果 4 或 5 
    如果 4 则打印四月
    打印五月
否则打印无效
英文:

In pseudo code, you could check all connected parts, without a break statement, together in a single statement and check the values in another nested if statement.

if 1 or 2
    if 1 print january
    print february
else if 3 print march
else if 4 or 5 
    if 4 print april
    print may
else print invalid

答案2

得分: 0

int month = input.nextInt();
if(month==1){
    System.out.println("一月");
    System.out.println("二月");
}else if(month==2){
    System.out.println("二月");
}
you should be able to repeat that for the next cases. Please try to clean up your code next time, if we are giving time to answer you should at least put in time to ask properly, thanks
英文:
int month = input.nextInt();
if(month==1){
    System.out.println(“January”);
    System.out.println(“February”);
}else if(month==2){
    System.out.println(“February”);
}

you should be able to repeat that for the next cases. Please try to clean up your code next time, if we are giving time to answer you should at least put in time to ask properly, thanks

huangapple
  • 本文由 发表于 2020年10月6日 14:33:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/64220498.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定