/** * Assignment 2, COMP268 Class: WeekDay.java * * @description A class used to determine the week day for any given date. * @author: mo khan Student ID: 3431709 * @date Jul 13, 2019 * @version 1.0 */ package Q6; import java.util.*; public class WeekDay { private static final String[] DAYS = new String[] {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}; private static final int[] MONTHS = new int[] {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; /** * Returns the day of the week that a certain date falls on. * * @param day the day of the month * @param month the month of the year * @param year the year * @return the name of the day of the week. (Sunday to Saturday) */ public String getWeekDay(int day, int month, int year) { this.ensureValidDate(year, month, day); return DAYS[daysSinceEpoch(day, month, year) % 7]; } private int daysSinceEpoch(int day, int month, int year) { int days = ((year - 1900) * 365) + ((year - 1900) / 4); if (isLeapYear(year) && (month == 1 || month == 2)) days -= 1; days += daysThisYearUpTo(day, month); return days; } private boolean isLeapYear(int year) { return year % 4 == 0; } private int daysThisYearUpTo(int day, int month) { int days = 0; for (int i = 1; i < month; i++) days += daysInMonth(i); return days + day; } private int daysInMonth(int month) { return MONTHS[month - 1]; } private void ensureValidDate(int year, int month, int day) { if (month < 1 || month > 12 || day < 1 || day > MONTHS[month - 1]) throw new IllegalArgumentException(); } /** * The entry point to the console application. * * @param args the argument vector given to the program. */ public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.println("--- Question 6 ---"); System.out.println("Enter year:"); int year = in.nextInt(); if (year < 1900 || year > 2100) { System.out.println("Invalid year."); System.exit(-1); } System.out.println("Enter month:"); int month = in.nextInt(); if (month < 1 || month > 12 || (year == 1900 && month < 3) || (year == 2100 && month > 2)) { System.out.println("Invalid month."); System.exit(-1); } System.out.println("Enter day:"); int day = in.nextInt(); System.out.println(); System.out.println("Today is:"); try { System.out.println(new WeekDay().getWeekDay(day, month, year)); } catch (IllegalArgumentException error) { System.out.println("Invalid date."); System.exit(-1); } System.out.println(); } }