-2

Is there any other way to shorten this particular piece of code. Any built in function in java to solve this problem. Anyway I have written simple code so that the people can understand what I want to ask.

enter code here
    if(month==1){
        month1="January";
    }
    if(month==2){
        month1="Febuary";
    }
    if(month==3){
        month1="March";
    }
    if(month==4){
        month1="April";
    }
    if(month==5){
        month1="May";
    }enter code here
    if(month==6){
        month1="June";
    }
    if(month==7){
        month1="July";
    }
    if(month==8){
        month1="August";
    }
    if(month==9){
        month1="September";
    }
    if(month==10){
        month1="October";
    }
    if(month==11){
        month1="November";
    }
    if(month==12){
        month1="December";
    }
Vaibs
  • 2,018
  • 22
  • 29
Yash Badia
  • 11
  • 3
  • Welcome to Stack Overflow! Please take the [tour](/tour), have a look around, and read through the [help center](/help), in particular [How do I ask a good question?](/help/how-to-ask) and [What topics can I ask about here?](/help/on-topic). **-** your quesion is unclear. does your code work? If so, You should delete your post here and ask your question at https://codereview.stackexchange.com – Timothy Truckle Sep 21 '17 at 14:31
  • 2
    https://stackoverflow.com/questions/1038570/how-can-i-convert-an-integer-to-localized-month-name-in-java – PhillipD Sep 21 '17 at 14:31

2 Answers2

2
private static final String[] MONTHS = {
        "January",
        "February",
        "March",
        "April",
        "May",
        "June",
        "July",
        "August",
        "September",
        "October",
        "November",
        "December",
};

/**
 * Returns the name of the month with the stated number.
 * 
 * @param monthNumber - The number is 1-based, i.e. 1 = January.
 * @return the name ofthe month as a string.
 */
public String getMonthName(int monthNumber) {
    return MONTHS[monthNumber - 1];
}
OldCurmudgeon
  • 64,482
  • 16
  • 119
  • 213
  • @yashbadia - Also be aware of [this](https://stackoverflow.com/questions/1038570/how-can-i-convert-an-integer-to-localized-month-name-in-java) technique which may be better still. – OldCurmudgeon Sep 22 '17 at 14:26
1
public static final String var[] = {"January","February","March"....,"December"};
and then

months = var[month];//or month-1 if you index from 1