Skip to content
Advertisement

a method that converts a daynumber into a date

A number between 1 and 365 is requested from the user. The number represents the day number of the year. The corresponding date is displayed.

I get stuck on the method calculationDateWithDayNumber

An example: the number 105 should be converted to date 15 April. My result is -31 February. Where does it go wrong?

public class DateOperations {
    
    private final static String[] MONTHS = {"January", "February", "March", "April", "May", "June", "July", "August", 
            "September", "October", "November", "December"  };
    
    private static final int[] NUMBERDAYS = {31,28,31,30,31,30,31,31,30,31,30,31};
    
    public static String calculationDateWithDayNumber(int day)
    {
        int month = 0;
        for (int i=0; day>=NUMBERDAYS[i] ;i++)  
            {day=-NUMBERDAYS[i];
            ++ month;}
             
            String nameMonth = MONTHS[month];

             
            
        String datum = String.format("%%d%%s",day, nameMonth);
        
        return datum;
    }

}

Advertisement

Answer

I guess you are practicing. Two fixes are needed, see below comments in code

day=-NUMBERDAYS[i] means you are assign value of (-1*NUMBERDAYS[i]) in day. But I think you should minus NUMBERDAYS[i] from day like day - NUMBERDAYS[i] and assign the value in day like day = day - NUMBERDAYS[i] or using shorthand operator like day -= NUMBERDAYS[i]

  public static String calculationDateWithDayNumber(int day) {
    int month = 0;
    for (int i = 0; day > NUMBERDAYS[i]; i++) {  // Fix here, remove equals since day can be last day of month
      day = day - NUMBERDAYS[i]; // Fix here, minus the NUMBERDAYS[i] from day
      ++month;
    }
    String nameMonth = MONTHS[month];
    String datum = String.format("%%d %%s", day, nameMonth);
    return datum;
  }

Output: 15 April

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement