输出返回Null

时间:2013-11-08 17:58:46

标签: java

我的类构建为输出月份和月份编号构建并运行正常,但在我的类中的某个地方,我的monthString被赋予null。我无法看到我遇到这个错误的地方,我为我的错误代码道歉。 TY! ~~~

public class MonthClass
{

private int monthNum;
private String monthString;



    public MonthClass(int num)
{
        monthNum = num;
        monthString = monthName(num);
}

    public void setmonthNum(int num)
{
        monthNum = num;
        monthString = monthName(num);
}   


public String getmonthName(int num)
{




 switch (num)
  {
 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= "Augest";
    break;
 case 9: monthString = "September";
    break;
 case 10: monthString = "October";
    break;
 case 11: monthString = "November";
    break;
 case 12: monthString = "December";
    break;
 default: monthString = "This is not a month, re-enter a number";
    break;

  }
  return monthString;
 }






    public String monthName(int num)
{
        return monthString;
}

public String toString()
{
return "The month number is " + monthNum + " and the month name is " + monthString;
}
}

1 个答案:

答案 0 :(得分:2)

问题在于,您的代码无处可修改monthString,其值始终为null(引用类型的默认值)。

而不是monthName你应该调用getmonthName(从月号到字符串的转换发生在那里):

monthString = getmonthName(num);

方法monthName只是 getter - 它不会修改monthString。此外,由于此方法不使用任何参数,您也可以摆脱它:

public String monthName() {
    return monthString;
}

此外,在default语句中的switch情况下,非月份字符串的分配将以静默方式发生。您可能还想在控制台上打印一些东西。