【发布时间】:2021-12-30 13:12:13
【问题描述】:
我遇到了关于数组中的索引超出范围错误的问题。 我想创建一个以月份和日期为参数并返回一年中的日期的方法。如果任何参数不正确,该方法应返回 0。
例如,如果方法接收到 2 和 3,即 2 月 3 日,它必须返回 34。如果它接收到 12 和 31,它必须返回 365。 但是我遇到了索引超出范围的问题并且无法解决任何提示。 这是我的代码。
公共类 CalendarMethods {
public static int dayInYear(int month, int day){
int[] daysInMonth = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
int yearCalculation = 0;
int monthCalculation = 0;
for (int j = 0; j < month-1; j++) {
monthCalculation = monthCalculation + daysInMonth[j];
}
yearCalculation = monthCalculation + day;
if (month <= 0 ) {
yearCalculation = 0;
}
if (month >= 13){
yearCalculation = 0;
}
return yearCalculation;
}
}
【问题讨论】:
-
你的 if(month >= 13) 在 for 循环之后被调用。因此,如果您使用 month = 14 (例如)调用您的函数,它将超出数组的范围,因为 j 上升到 13 > 11 并且您的数组只有 12 个元素。为防止这种情况发生,您应该提前返回或使用 if else 语句
标签: arrays indexing calendar indexoutofboundsexception arrayindexoutofboundsexception