java使用switch输出月份
时间: 2024-10-21 12:03:23 浏览: 17
在Java中,你可以使用`switch`语句结合字符串匹配来根据月份名称输出对应的数字表示。假设你想将月份名转换成月份编号(如"January"对应1),可以这样做:
```java
String month = "January"; // 或者其他月份名称
int monthNumber;
switch (month.toLowerCase()) {
case "january":
monthNumber = 1;
break;
case "february":
monthNumber = 2;
break;
case "march":
monthNumber = 3;
break;
case "april":
monthNumber = 4;
break;
case "may":
monthNumber = 5;
break;
case "june":
monthNumber = 6;
break;
case "july":
monthNumber = 7;
break;
case "august":
monthNumber = 8;
break;
case "september":
monthNumber = 9;
break;
case "october":
monthNumber = 10;
break;
case "november":
monthNumber = 11;
break;
case "december":
monthNumber = 12;
break;
default:
System.out.println("Invalid month");
}
System.out.println("Month number is: " + monthNumber);
```
在这个例子中,如果输入的是有效的月份名称,它会输出相应的月份编号;如果不是,则会打印出"Invalid month"。
阅读全文