在这里我试图通过输入月份数来获得输出月份,但为什么我有错误 - "monthString"可能尚未初始化? - 为什么我没有从"monthString"获取输出字符串?
为什么monthString必须初始化?import java.util.Scanner; public class SwitchClass { public static void main(String[]args) { Scanner input = new Scanner(System.in); System.out.printf(" when did u born ? "); int monthNumber = input.nextInt(); String monthString ; switch (monthNumber) { case 1: monthString = "January "; break; case 2: monthString = "February "; break; case 3: monthString = "March "; break; case 4: monthString = "April "; break; case 5: monthString = "May"; break; case 6: monthString = "June"; break; case 7: monthString = "July"; break; case 8: monthString = "August"; break; case 9: monthString = "September"; break; case 10: monthString = "October"; break; case 11: monthString = "November"; break; case 12: monthString = "December"; break; } System.out.println(monthString); } }
Eran.. 8
如果monthNumber
不在1到12之间怎么办?在这种情况下,monthString
不会被初始化.您声明时应该给它一些默认值:
String monthString = null; // or ""
或者创建一个默认的开关案例,为它提供一个值. (4认同)
Redtama.. 5
在switch语句中添加一个默认大小写是个好主意.
例:
switch (monthNumber) { case 1: monthString = "January"; break; //other cases... default: monthString = "Invalid Month Number"; break; }
这种方式如果monthNumber
不是1-12那么仍然存在switch语句流向的默认情况.
如果monthNumber
不在1到12之间怎么办?在这种情况下,monthString
不会被初始化.您声明时应该给它一些默认值:
String monthString = null; // or ""
在switch语句中添加一个默认大小写是个好主意.
例:
switch (monthNumber) { case 1: monthString = "January"; break; //other cases... default: monthString = "Invalid Month Number"; break; }
这种方式如果monthNumber
不是1-12那么仍然存在switch语句流向的默认情况.