int day = 3; String dayName; switch (day) { case 1: dayName = "Monday"; case 2: dayName = "Tuesday"; break; case 3: dayName = "Wednesday"; case 4: dayName = "Thursday"; case 5: dayName = "Friday"; case 6: dayName = "Saturday"; break; case 7: dayName = "Sunday"; default: dayName = "Invalid day"; break;}
时间: 2024-02-14 11:18:23 浏览: 67
SwitchCaseTest_javaswitchcase_
这段代码是一个使用 switch 语句的示例,其目的是根据变量 day 的值来确定对应的星期几名称,然后将其存储在变量 dayName 中。具体来说,代码首先定义了一个整数变量 day,并初始化为 3。然后使用 switch 语句分别处理 day 取不同值时的情况。在每个 case 标签下,对应的语句块会被执行,直到遇到 break 语句或者 switch 语句结束为止。在此代码中,当 day 取值为 3 时,dayName 被赋值为 "Wednesday",但是由于缺少 break 语句,程序会继续执行下去,直到执行到 default 标签处,dayName 被赋值为 "Invalid day"。因此,该代码的输出结果为 "Invalid day"。如果你想要 day 取值为 3 时输出 "Wednesday",应该在 case 3 标签下添加一个 break 语句,如下所示:
```
int day = 3;
String dayName;
switch (day) {
case 1:
dayName = "Monday";
break;
case 2:
dayName = "Tuesday";
break;
case 3:
dayName = "Wednesday";
break;
case 4:
dayName = "Thursday";
break;
case 5:
dayName = "Friday";
break;
case 6:
dayName = "Saturday";
break;
case 7:
dayName = "Sunday";
break;
default:
dayName = "Invalid day";
break;
}
```
阅读全文