I'm encountering "a variable might not have been initialized" error when using switch block.
Here is my code:
public static void foo(int month)
{
String monthString;
switch (month)
{
case 1: monthString = "January";
break;
case 2: monthString = "February";
break;
}
System.out.println(monthString);
}
The error:
Switch.java:17: error: variable monthString might not have been initialized
System.out.println (monthString);
To my knowledge this error occurs when you try access a variable you have not initialized, but am I not initializing it when I assign it the value in the switch block?
Similarly, even if the month is a compile-time constant, I still receive the same error:
public static void foo()
{
int month = 2;
String monthString;
switch (month)
{
case 1: monthString = "January";
break;
case 2: monthString = "February";
break;
}
System.out.println(monthString);
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…