java随机产生一个1到12之间的整数,根据1~12显示相应的英文月份:January,Februray,...,December。
时间: 2023-07-15 13:12:38 浏览: 236
可以使用Java中的Math.random()方法和switch语句来实现:
```java
int month = (int)(Math.random() * 12) + 1; // 产生1到12之间的随机整数
String monthName;
switch(month) {
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;
default:
monthName = "December";
break;
}
System.out.println(monthName);
```
上述代码中,首先使用Math.random()方法生成1到12之间的随机整数,然后使用switch语句根据整数值选择相应的月份名称,并将其存储在字符串变量monthName中。最后使用System.out.println()方法将其输出。
阅读全文