我有以下代码:
switch(month){
case 1:
System.out.print("January");
break;
case 2:
System.out.print("February");
break;
case 3:
System.out.print("March");
break;
case 4:
System.out.print("April");
break;
case 5:
System.out.print("May");
break;
case 6:
System.out.print("June");
break;
case 7:
System.out.print("July");
break;
case 8:
System.out.print("August");
break;
case 9:
System.out.print("September");
break;
case 10:
System.out.print("October");
break;
case 11:
System.out.print("November");
break;
case 12:
System.out.print("December");
break;
}
好的,这段代码在int月份中可以100%完美地工作。我有另一个int(avgMonth),它只能容纳相同的值(1-12),而我只希望具有相同的输出(月份)。如何将avgMonth添加到此代码,而不必复制整个开关和大小写?
我尝试使用逗号(month,avgMonth)和&&的(month && avgMonth)以及+的(month + avgMonth),但无济于事。
最佳答案
将整个代码块封装在一个方法中,然后将avgMonth
和month
作为参数传递。像这样:
public static void monthNumToName(int month) {
// … same as before
}
另外,您可以使用
Map
简化代码:private static final Map<Integer, String> months;
static {
months.put(1, "January");
months.put(2, "February");
months.put(3, "March");
months.put(4, "April");
months.put(5, "May");
months.put(6, "June");
months.put(7, "July");
months.put(8, "August");
months.put(9, "September");
months.put(10, "October");
months.put(11, "November");
months.put(12, "December");
}
public static void monthNumToName(int month) {
String name = months.get(month);
if (name == null)
throw new IllegalArgumentException("Invalid month number: " + month);
System.out.print(name);
}
甚至更简单,只需使用一个数组,因为我们事先知道月份数限制在1-12范围内:
private static final String[] months = {
"January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
};
public static void monthNumToName(int month) {
if (month < 1 || month > 12)
throw new IllegalArgumentException("Invalid month number: " + month);
System.out.print(months[month-1]);
}
无论如何,当您需要打印月份名称时,请执行以下操作:
monthNumToName(month);
monthNumToName(avgMonth);
关于java - 同一情况下的多个开关,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21647854/