Function Java—比使用Ifs和重复函数更好的方法—与日期相关
我创建了一个函数来检查我的日期字符串所包含的月份,这样我就可以将它用于多种日期格式。但是我使用了很多ifs并重复了.contains函数。有更好的方法吗 另外,我的相关日期格式为工作日(字符串)、月(字符串)日(int-XX)、年(int-XXXX)。e、 g.1965年6月27日,星期日。到目前为止,我在内置函数方面还不太走运Function Java—比使用Ifs和重复函数更好的方法—与日期相关,function,date,if-statement,switch-statement,contains,Function,Date,If Statement,Switch Statement,Contains,我创建了一个函数来检查我的日期字符串所包含的月份,这样我就可以将它用于多种日期格式。但是我使用了很多ifs并重复了.contains函数。有更好的方法吗 另外,我的相关日期格式为工作日(字符串)、月(字符串)日(int-XX)、年(int-XXXX)。e、 g.1965年6月27日,星期日。到目前为止,我在内置函数方面还不太走运 public static int CheckMonth(String s){ String month = s.toLowerCase();
public static int CheckMonth(String s){
String month = s.toLowerCase();
if(month.contains("january")){return 1;}
else if(month.contains("febuary")){return 2;}
else if(month.contains("march")){return 3;}
else if(month.contains("april")){return 4;}
else if(month.contains("may")){return 5;}
else if(month.contains("june")){return 6;}
else if(month.contains("july")){return 7;}
else if(month.contains("august")){return 8;}
else if(month.contains("september")){return 9;}
else if(month.contains("october")){return 10;}
else if(month.contains("november")){return 11;}
else if(month.contains("december")){return 12;}
else {return -1;}
}
你可以使用一个循环。比如说,
// 'lookup'
static String[] monthNames = {"january", .., "december"};
// in method
for (var i = 0; i < months.length; i++) {
if (monthName.contains(monthNames[i])) {
return i + 1; // because 0..11 indices in array
}
}
// do something if no matching month was found
//“查找”
静态字符串[]monthNames={“一月”,“十二月”};
//方法
对于(变量i=0;i
尽管尝试“NLP”日期,但我确信存在现有库。对于要执行的操作,可以使用枚举存储文本和数字。例如:
public enum Month {
JANUARY("january", 1), FEBRUARY("february", 2) ... DECEMBER("december", 12);
private final String string;
private final int number;
private Month(String string, int number) {
this.string = string;
this.number = number;
}
public int getMonthNumber(String string) {
for(Month month : Month.values()) {
if(string.contains(this.string))
return month.number
}
return -1;
}
}
是的,有,但到目前为止,我还没找到他们。反正这更整洁。非常感谢。