【发布时间】:2021-12-29 05:23:27
【问题描述】:
当 Calendar instance = Calendar.getInstance(); 时,我实现了小的 if-else 部分来获取月份的前三个字母;检索月份的整数值。我想将它用作可重用的功能。我尝试过创建另一个 java 文件,但它想要工作。谁能告诉我如何使用它?
public class MstrMonth {
public MstrMonth() {}
public static String getCurrentMonth(String currentMonth) {
Calendar instance = Calendar.getInstance();
int mMonth = instance.get(Calendar.MONTH) + 1;
if(mMonth == 1){
currentMonth = "JAN";
}else if (mMonth == 2){
currentMonth = "FEB";
}else if (mMonth == 3){
currentMonth = "MAR";
}else if (mMonth == 4){
currentMonth = "APR";
}else if (mMonth == 5){
currentMonth = "MAY";
}else if (mMonth == 6){
currentMonth = "JUN";
}else if (mMonth == 7){
currentMonth = "JUL";
}else if (mMonth == 8){
currentMonth = "AUG";
}else if (mMonth == 9){
currentMonth = "SEP";
}else if (mMonth == 10){
currentMonth = "OCT";
}else if (mMonth == 11){
currentMonth = "NOV";
}else if (mMonth == 12){
currentMonth = "DEC";
}
return currentMonth;
}
}
在主要活动中;
String currentMonth;
MstrMonth.getCurrentMonth(currentMonth);
我想在这里获取月份代码,但它给出了空值。
【问题讨论】:
-
您需要将方法的返回值分配给某些东西...分配给参数不会影响调用代码(改变参数会,但这对于字符串来说是不可能的,因为它们是不可变)。
标签: java null coding-style reusability