我应该以yyyy“” mm“” dd的形式插入一个参数,同时使用“ /”,“。”或“-”作为分隔符。该程序可以识别使用了哪个分隔符,其他功能无关。但是,如果可以肯定的话,有太多其他方法可以重写或替换为更干净的代码。 有什么建议吗?
static String[] weekDays = new String[] {
"Sun", "Mon", "Tues", "Wednes", "Thurs", "Fri", "Satur"
};
enum weekDays {SUN,MON,TUES,WEDNES,THURS,FRI,SATUR};
static void setCalendarDate(final Calendar cal, final String date, final String seperator) {
final String[] splitDate = date.split(seperator);
cal.set(parseInt(splitDate[0]), parseInt(splitDate[1]) - 1, parseInt(splitDate[2]));
}
public static void main(final String[] args) {
final Calendar cal = Calendar.getInstance();
if (args.length != 0) {
if (args[0].contains("-")) {
setCalendarDate(cal, args[0], "-");
} else if (args[0].contains("/")) {
setCalendarDate(cal, args[0], "/");
} else if (args[0].contains(".")) {
setCalendarDate(cal, args[0],".");
}
}
final int weekDay = cal.get(Calendar.DAY_OF_WEEK);
System.out.printf("%sday\n", weekDays[weekDay - 1]);
}
}
答案 0 :(得分:1)
我个人将存储有效的分隔符数组,如下所示:
static final String[] validSeparators = new String[] {"-","/","."};
您可以将分隔符检查移至setCalendarDate
方法本身,检查字符串是否包含任何适当的字符。然后,我将重构该方法以在无效的分隔符上引发异常,并删除分隔符参数。
static void setCalendarDate(final Calendar cal, final String date) throws ParseException{
String separator = null;
for(String s : validSeparators) {
if(date.contains(s)) {
separator = s;
break;
}
}
if(separator == null) {
throw new ParseException("No valid separator found", 0);
}
final String[] splitDate = date.split(separator);
cal.set(Integer.parseInt(splitDate[0]), Integer.parseInt(splitDate[1]) - 1, Integer.parseInt(splitDate[2]));
}
另一种选择是检查日期字符串的特定字符:
static void setCalendarDate(final Calendar cal, final String date) throws ParseException{
String separator = String.valueOf(date.charAt(4));
if(Arrays.asList(validSeparators).contains(separator)) {
final String[] splitDate = date.split(separator);
cal.set(Integer.parseInt(splitDate[0]), Integer.parseInt(splitDate[1]) - 1, Integer.parseInt(splitDate[2]));
} else {
throw new ParseException("Valid separator not found", 0);
}
}
如果您想要额外的安全性,还可以检查第7个字符并在分割前进行比较。
最后,您的主体现在看起来像这样:
final Calendar cal = Calendar.getInstance();
if (args.length != 0) {
try {
setCalendarDate(cal, args[0]);
} catch (ParseException ex) {
ex.printStackTrace();
}
}
final int weekDay = cal.get(Calendar.DAY_OF_WEEK);
System.out.printf("%sday\n", weekDays[weekDay - 1]);