【问题标题】:any shorter method to do reduce this piece of code? [duplicate]有什么更短的方法可以减少这段代码吗? [复制]
【发布时间】:2018-03-02 23:06:47
【问题描述】:

有没有其他方法可以缩短这段特定的代码。 java中的任何内置函数都可以解决这个问题。 无论如何,我已经编写了简单的代码,以便人们能够理解我想问的内容。

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";
    }

【问题讨论】:

标签: java if-statement refactoring


【解决方案1】:
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];
}

【讨论】:

  • 非常感谢...
  • @yashbadia - 还要注意this 技术,这可能会更好。
【解决方案2】:
public static final String var[] = {"January","February","March"....,"December"};
and then

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

【讨论】:

  • 非常感谢...
猜你喜欢
  • 2023-04-10
  • 1970-01-01
  • 2012-01-24
  • 1970-01-01
  • 1970-01-01
  • 2020-03-05
  • 2022-11-22
  • 1970-01-01
  • 2019-07-26
相关资源
最近更新 更多