gpt4 book ai didi

java - 同一案例的多个开关

转载 作者:行者123 更新时间:2023-11-29 09:48:09 25 4
gpt4 key购买 nike

我有这个代码:

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;
}

好吧,这段代码 100% 完美地工作......对于 int 月。我有另一个 int (avgMonth),它只能保存相同的值 (1-12),我只想有相同的输出(月份)。如何将 avgMonth 添加到此代码而不必复制我的整个开关和外壳?我尝试使用逗号 (month, avgMonth) 和 &&'s (month && avgMonth) 以及 +'s (month + avgMonth) 但无济于事。

最佳答案

将整个代码块封装在一个方法中,并将avgMonthmonth 作为参数传递。像这样:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com