getting unexpected outputs in a question which asks to tell the day from date

Viewed 62

This question is from a website and part of the code was already given by them (the solution class) asked to make a program that tells day based on date.

I have made the result class and the outputs are sometimes correct and sometimes not there is no compilation error. Can anyone please tell where the logical error lies.

ALSO CAN SOMEONE tell a better way of doing this like a bit lesser code. Thanks in advance.

import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
import java.util.regex.*;
import java.util.stream.*;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;

class Result {
    int month,day,year;
    public static boolean leap(int year){
        if(year%400==0){
            return true;
        }
        else if(year%100==0){
            return false;
        }else if(year%4==0){
            return true;
        }else{
            return false;
        }
    };
    public static int year_count(int year){
        int count=0;
        for(int i=2000;i<year;i++){
            if(leap(year)){
                count += 366;
            }
            else{
                count += 365;
            }
        };
        return count;
        
    };
    public static int month_count(int m,int y){
        int k=m-1;
        int [] ny = {31,28,31,30,31,30,31,31,30,31,30,31};
        int [] ly = {31,29,31,30,31,30,31,31,30,31,30,31};
        if(leap(y)){
            if(k==1){
                return 31;
            }
            else{
                return ly[k] + month_count(k-1,y);
            }
        }else{
            if(k==1){
                return 31;
            }
            else{
                return ny[k] + month_count(k-1,y);
            }
        }
    };
    public static int total_count(int d,int m,int y){
        return d+month_count(m,y)+year_count(y);
      
    }
   
    public static String findDay(int month, int day, int year) {
        int n = total_count(day,month,year) % 7;
        String [] days={"MONDAY","TUESDAY","WEDNESDAY","THURSDAY","FRIDAY","SATURDAY","SUNDAY"};
        return days[n];


        

    }

}
//no need check this below part as it was given by the browser from which the question was taken

public class Solution {
    public static void main(String[] args) throws IOException {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));

        String[] firstMultipleInput = bufferedReader.readLine().replaceAll("\\s+$", "").split(" ");

        int month = Integer.parseInt(firstMultipleInput[0]);

        int day = Integer.parseInt(firstMultipleInput[1]);

        int year = Integer.parseInt(firstMultipleInput[2]);

        String res = Result.findDay(month, day, year);

        bufferedWriter.write(res);
        bufferedWriter.newLine();

        bufferedReader.close();
        bufferedWriter.close();
    }
}

THE OUTPUT IS CORRECT FOR :

1.02 13 2010 which gives SATURDAY

2.08 05 2015 which gives WEDNESDAY

THE OUTPUT IS NOT CORRECT FOR:

  1. 02 29 2004 which is giving SATURDAY but should give SUNDAY
  2. 08 05 2999 which is giving SUNDAY but should give MONDAY
  3. 04 06 2012 which is giving MONDAY but should give FRIDAY
3 Answers

There are a few mistakes in the code.

Mistake 1:

year_count checks if the year passed in is a leap year, not the year you iterate over in the loop. Change to:

    for(int i=2000;i<year;i++){
        if(leap(i))

Mistake 2:

month_count skips over months. Since k=m-1, the recursive call to month_count should use k, not k-1. Also it uses the wrong index to look up the number of days from the wrong index. Change to:

            return ly[k-1] + month_count(k,y);

and to:

            return ny[k-1] + month_count(k,y);

Mistake 3:

findDay assumes that Jan 1 2000 was a Sunday. It was a Saturday. The array of days should therefore start with FRIDAY:

    String [] days={"FRIDAY","SATURDAY","SUNDAY","MONDAY","TUESDAY","WEDNESDAY","THURSDAY"};

ALSO CAN SOMEONE tell a better way of doing this like a bit lesser code.

Use the standard library classes in the java.time package:

public static String findDay(int month, int day, int year) {
    return LocalDate.of(year, month, day).getDayOfWeek().name();
}

I suggest you do it by using the java.time date-time API. Learn more about this modern date-time API from Trail: Date Time.

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

public class Main {
    public static void main(String[] args) {
        // Test strings
        String[] dateStrings = { "02 13 2010", "08 05 2015", "02 29 2004", "08 05 2999", "04 06 2012" };

        // Define formatter
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM dd uuuu");

        for (String dateString : dateStrings) {
            System.out.println(LocalDate.parse(dateString, formatter).getDayOfWeek());
        }
    }
}

Output:

SATURDAY
WEDNESDAY
SUNDAY
MONDAY
FRIDAY

I don't know what your code is going wrong, but I can suggest a better way to do it: there is a Calendar Class (java.util.Calendar) in java which can be used to solve this problem:

public static String findDay(int month, int day, int year) {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.MONTH, month-1);
        cal.set(Calendar.DAY_OF_MONTH, day);
        cal.set(Calendar.YEAR, year);

        String[] day_of_week = {"SUNDAY", "MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY","SATURDAY"};

        return day_of_week[cal.get(Calendar.DAY_OF_WEEK)-1];

    }
}
Related