master
1/**
2 * Assignment 2, COMP268 Class: WeekDay.java
3 *
4 * @description A class used to determine the week day for any given date.
5 * @author: mo khan Student ID: 3431709
6 * @date Jul 13, 2019
7 * @version 1.0
8 */
9package Q6;
10
11import java.util.*;
12
13public class WeekDay {
14 private static final String[] DAYS =
15 new String[] {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
16 private static final int[] MONTHS = new int[] {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
17
18 /**
19 * Returns the day of the week that a certain date falls on.
20 *
21 * @param day the day of the month
22 * @param month the month of the year
23 * @param year the year
24 * @return the name of the day of the week. (Sunday to Saturday)
25 */
26 public String getWeekDay(int day, int month, int year) {
27 this.ensureValidDate(year, month, day);
28 return DAYS[daysSinceEpoch(day, month, year) % 7];
29 }
30
31 private int daysSinceEpoch(int day, int month, int year) {
32 int days = ((year - 1900) * 365) + ((year - 1900) / 4);
33 if (isLeapYear(year) && (month == 1 || month == 2)) days -= 1;
34 days += daysThisYearUpTo(day, month);
35 return days;
36 }
37
38 private boolean isLeapYear(int year) {
39 return year % 4 == 0;
40 }
41
42 private int daysThisYearUpTo(int day, int month) {
43 int days = 0;
44 for (int i = 1; i < month; i++) days += daysInMonth(i);
45 return days + day;
46 }
47
48 private int daysInMonth(int month) {
49 return MONTHS[month - 1];
50 }
51
52 private void ensureValidDate(int year, int month, int day) {
53 if (month < 1 || month > 12 || day < 1 || day > MONTHS[month - 1])
54 throw new IllegalArgumentException();
55 }
56
57 /**
58 * The entry point to the console application.
59 *
60 * @param args the argument vector given to the program.
61 */
62 public static void main(String[] args) {
63 Scanner in = new Scanner(System.in);
64
65 System.out.println("--- Question 6 ---");
66 System.out.println("Enter year:");
67 int year = in.nextInt();
68 if (year < 1900 || year > 2100) {
69 System.out.println("Invalid year.");
70 System.exit(-1);
71 }
72
73 System.out.println("Enter month:");
74 int month = in.nextInt();
75 if (month < 1 || month > 12 || (year == 1900 && month < 3) || (year == 2100 && month > 2)) {
76 System.out.println("Invalid month.");
77 System.exit(-1);
78 }
79
80 System.out.println("Enter day:");
81 int day = in.nextInt();
82
83 System.out.println();
84 System.out.println("Today is:");
85
86 try {
87 System.out.println(new WeekDay().getWeekDay(day, month, year));
88 } catch (IllegalArgumentException error) {
89 System.out.println("Invalid date.");
90 System.exit(-1);
91 }
92 System.out.println();
93 }
94}