class Result {
public static String findDay(int month, int day, int year) {
String [] B = {"MONDAY","TUESDAY","WEDNESDAY","THURSDAY","FRIDAY","SATURDAY","SUNDAY"};
Calendar A = Calendar.getInstance();
A.set(Calendar.MONTH, month-1);
A.set(Calendar.YEAR, year);
A.set(Calendar.DAY_OF_MONTH,day);
return B[A.get(Calendar.DAY_OF_WEEK)-2];
}
}
对于其中一个测试用例,我遇到了上述代码的运行时错误。我不明白为什么,请您解释一下以后如何解决这种运行时错误。
答案 0 :(得分:0)
我在这段代码中看到2个问题,它们都是关于索引的。 我建议使用此版本:
public static String findDay(int month, int day, int year) {
String [] B = {"MONDAY","TUESDAY","WEDNESDAY","THURSDAY","FRIDAY","SATURDAY","SUNDAY"};
Calendar A = Calendar.getInstance();
final int monthIndex = (month + 11) % 12;
A.set(Calendar.MONTH, monthIndex);
A.set(Calendar.YEAR, year);
A.set(Calendar.DAY_OF_MONTH,day);
final int dayIndex = (A.get(Calendar.DAY_OF_WEEK) + 5) % 7;
return B[dayIndex];
}
如您所见,我使用模仍然在数组“ B”的索引范围内。我对“月指数”也是如此。