Java输入相应月份的数字时,打印出相应月份的英文
时间: 2024-09-19 21:14:56 浏览: 31
java检测输入的字符是否是数字
5星 · 资源好评率100%
当你在Java中编写程序,想要根据用户输入的月份数字对应输出英文名称时,可以创建一个方法来实现这个功能。这里是一个简单的示例:
```java
import java.util.Scanner;
public class MonthConverter {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入月份数字(1-12):");
int monthNumber = scanner.nextInt();
String monthName;
switch (monthNumber) {
case 1:
monthName = "January";
break;
case 2:
monthName = "February";
break;
case 3:
monthName = "March";
break;
case 4:
monthName = "April";
break;
case 5:
monthName = "May";
break;
case 6:
monthName = "June";
break;
case 7:
monthName = "July";
break;
case 8:
monthName = "August";
break;
case 9:
monthName = "September";
break;
case 10:
monthName = "October";
break;
case 11:
monthName = "November";
break;
case 12:
monthName = "December";
break;
default:
monthName = "Invalid input! Please enter a number between 1 and 12.";
break;
}
System.out.println("对应的英文月份是: " + monthName);
}
}
```
在这个例子中,我们使用了`switch`语句来根据输入的月份数字匹配相应的英文名称。如果输入超出范围,会给出错误提示。
阅读全文