Мое задание - отформатировать форматированный строковый месяц # - NNNN (где знак # - значение поля monthNumber
, а NNNN - значение поля monthName
. Проблема в том, что когда я нажимаю getMonthName
, он выходит на 'нуль'.Оператор Switch с пометками
Как это исправить?
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;
}
}
Я пробовал это и все еще имел «нуль». – Prohew
Ну, чтобы исправить себя во времени, String не совсем примитивный тип, но все же неизменный. – Victor