我的任务是打印格式化的String Month#,是NNNN(其中#号是字段monthNumber
的值,而NNNN是字段monthName
的值。问题是,当我单击getMonthName
时,它显示为'空值'。
我该如何解决?
public class Month {
// instance variables - replace the example below with your own
private int monthNumber;
private String monthName;
private String newMonthName;
/**
* Constructor for objects of class Month
*/
public Month(int input){
if((input == 0) || (input > 12)){
System.out.println("Error: Month number must be between 1 and 12");
}
else if(input < 0){
System.out.println("Error: Month number must be positive");
}
else{ //the value of the input is valid
System.out.println("Month number is VALID");
}
setMonthName(monthName);
printMonth(input);
monthNumber = input;
}
/**
*
*/
private void setMonthName(String monthName)
{
switch(monthNumber){
case 1:
monthName = "January";
break;
case 2:
monthName = "February";
break;
case 3:
monthName = "March";
break;
case 4:
monthName = "April";
break;
case 5:
monthName = "May";
break;
case 6:
monthName = "June";
break;
case 7:
monthName = "July";
break;
case 8:
monthName = "August";
break;
case 9:
monthName = "September";
break;
case 10:
monthName = "October";
break;
case 11:
monthName = "November";
break;
case 12:
monthName = "December";
break;
default:
monthName = "Invalid month";
break;
}
}
/**
*
*/
private void printMonth(int input)
{
switch(input){
case 0:
System.out.println("Month " + input + " is not a month");
break;
case 1:
System.out.println("Month " + input + " is January");
break;
case 2:
System.out.println("Month " + input + " is February");
break;
case 3:
System.out.println("Month " + input + " is March");
break;
case 4:
System.out.println("Month " + input + " is April");
break;
case 5:
System.out.println("Month " + input + " is May");
break;
case 6:
System.out.println("Month " + input + " is June");
break;
case 7:
System.out.println("Month " + input + " is July");
break;
case 8:
System.out.println("Month " + input + " is August");
break;
case 9:
System.out.println("Month " + input + " is September");
break;
case 10:
System.out.println("Month " + input + " is October");
break;
case 11:
System.out.println("Month " + input + " is November");
break;
case 12:
System.out.println("Month " + input + " is December");
break;
default:
System.out.println("Month " + input + "is an invalid month");
break;
}
}
/**
*
*/
public int getMonthNumber()
{
return monthNumber;
}
/**
*
*/
public String getMonthName()
{
return monthName;
}
}
最佳答案
抱歉,您似乎只在调用monthNumber
之后才分配setMonthName()
。
在您的构造函数中重新排列代码:
monthNumber = input;
setMonthName();
printMonth(input);
同样,在
setMonthName()
中,您将分配给参数,由于具有相同的名称,该参数使该类中的字段蒙上了阴影。 (最好在IDE中打开该警告)。从setMonthName()
中删除参数,然后您将在对象中实际设置该字段。private void setMonthName()
{
switch(monthNumber){
[...]
}
}
最后,与您提出的问题无关,我建议更改
printMonth(int input)
以使用对象中的字段,而不是从setMonthName()
复制您的switch语句。关于java - 用几个月切换语句,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32876667/