Java 有没有更短的方法来减少这段代码?
有没有其他方法可以缩短这段代码。 java中解决此问题的任何内置函数。 无论如何,我已经编写了简单的代码,以便人们能够理解我想问的问题Java 有没有更短的方法来减少这段代码?,java,if-statement,refactoring,Java,If Statement,Refactoring,有没有其他方法可以缩短这段代码。 java中解决此问题的任何内置函数。 无论如何,我已经编写了简单的代码,以便人们能够理解我想问的问题 enter code here if(month==1){ month1="January"; } if(month==2){ month1="Febuary"; } if(month==3){ month1="March"; } if(month==4){
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";
}
欢迎来到堆栈溢出!请拿着这本书,四处看看,仔细阅读,尤其是和你的问题不清楚。你的代码有效吗?如果是这样的话,你应该在这里删除你的帖子,并在“非常感谢你”网站上询问你的问题…@yashbadia-还要注意可能更好的技巧。非常感谢你。。。
public static final String var[] = {"January","February","March"....,"December"};
and then
months = var[month];//or month-1 if you index from 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];
}