Home > front end >  Index out of bound, java
Index out of bound, java

Time:12-31

I have a problem regarding index out of bound error in arrays. I want to create a method that takes month and day as parameter and returns day of the year.If any of the parameters are incorrect, the method should return 0.

for example if the method receives 2 and 3, meaning the third of February it must return 34. If it receives 12 and 31, it must return 365. but I am getting this problem of index out of bound and can't solv it any tips. this is my code.

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;
    

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

}

CodePudding user response:

You should do the boundary checks on month before the loop. A fix for that would be:

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

CodePudding user response:

For functions, always do sanity checks first to ensure the inputs you are getting align with your expections, in this this case we expect months to be values between 1 and 12 so same implementation as you had but check inputs before processing the rest of the code. This saves you from exceptions from unexpected/bad inputs.

   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;
        
    }
  • Related