对于上述程序,我在一个测试用例中遇到运行时错误。所有其余的测试用例都通过了。有什么建议么

时间:2019-11-12 15:25:35

标签: java

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];
      }

}

对于其中一个测试用例,我遇到了上述代码的运行时错误。我不明白为什么,请您解释一下以后如何解决这种运行时错误。

1 个答案:

答案 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”的索引范围内。我对“月指数”也是如此。