【问题标题】:Index out of bound, java索引超出范围,java
【发布时间】: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


【解决方案1】:

您应该在循环前一个月进行边界检查。解决方法是:

    public class 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;

        if (month > 0 && month < 13) {
           if (day > 0 && day <= daysInMonth[month - 1]) { // extra: check if entered day makes sense
             for (int j = 0; j < month-1; j++) {
               monthCalculation = monthCalculation + daysInMonth[j];
             }
        
             yearCalculation = monthCalculation + day;
          }
       }

        return yearCalculation;
    }
}

【讨论】:

    【解决方案2】:

    对于函数,请始终先进行健全性检查,以确保您获得的输入符合您的预期,在这种情况下,我们预计月份的值在 1 到 12 之间,因此与您的实现相同,但在处理其余部分之前检查输入的代码。这使您免于意外/错误输入的异常。

       public static int dayInYear(int month, int day){
    
    
            if (month <= 0||month >= 13 ) {
               return 0;
            }
       
        
            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;
           
            return yearCalculation;
            
        }
    

    【讨论】:

    • 哟谢谢大家,开始更多地使用这个页面。惊人的帮助。将永远记住健全性检查。
    猜你喜欢
    • 2015-04-12
    • 1970-01-01
    • 1970-01-01
    • 2014-03-02
    • 1970-01-01
    • 2018-03-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多