-20

我收到一个编译器错误,指出该变量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;
        }
}
4

3 回答 3

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变量是不需要的。

于 2013-05-20T08:07:27.570 回答
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);
于 2013-05-20T08:06:56.820 回答
0

如错误所述,您尝试nameOfMonth在初始化之前使用变量 ( ) 值。

你需要使用:

month=ConsoleInput.readInt("Enter Month in the form, e.g- January = 1, Febuary = 2, etc");
String monthString = nameOfMonth(month);

因为你并没有真正使用nameOfMonth变量,而是nameOfMonth 方法

于 2013-05-20T08:07:14.707 回答