我收到编译错误,说明变量nameOfMonth
可能尚未初始化。
我知道这可能是一个简单的解决办法,但我很困难,似乎无法在Google上找到答案。
public class Switch
{
public static void main ( String [] args )
{
int month;
String monthString, nameOfMonth;
month=ConsoleInput.readInt("Enter Month in the form, e.g- January = 1, Febuary = 2, etc");
monthString = nameOfMonth;
System.out.println(monthString);
}
protected static String nameOfMonth(int month)
{
String monthString;
switch(month)
{
case 1: monthString = "January";
break;
case 2: monthString = "Febuary";
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;
default: monthString = "Invalid Month";
break;
}
return monthString;
}
}
答案 0 :(得分:2)
nameOfMonth
在作业的右侧使用之前未初始化:
String monthString, nameOfMonth;
month=ConsoleInput.readInt(
"Enter Month in the form, e.g- January = 1, Febuary = 2, etc");
monthString = nameOfMonth; // Correct compiler error here.
我怀疑代码意味着调用相同的命名方法。
monthString = nameOfMonth(month);
并且nameOfMonth
变量是不需要的。
答案 1 :(得分:0)
您想要调用名为nameOfMonth
的方法,您不希望声明具有该名称的另一个字符串。改变
String monthString, nameOfMonth;
month=ConsoleInput.readInt("Enter Month in the form, e.g- January = 1, Febuary = 2, etc");
monthString = nameOfMonth;
System.out.println(monthString);
到
String month=ConsoleInput.readInt("Enter Month in the form, e.g- January = 1, Febuary = 2, etc");
String monthString = nameOfMonth(month);
System.out.println(monthString);
答案 2 :(得分:0)
如错误所述,您尝试在初始化之前使用变量(nameOfMonth
)值。
您需要使用:
month=ConsoleInput.readInt("Enter Month in the form, e.g- January = 1, Febuary = 2, etc");
String monthString = nameOfMonth(month);
由于您并非真正使用nameOfMonth
变量,而是nameOfMonth
方法。