/******************************* FILE HEADER ********************************** Main: Oops4.java File: Date.java Author: James D. Skrentny, skrentny@cs.wisc.edu copyright 2000 all rights reserved Course: CS 302: Lectures 1 & 2 Compiler: CodeWarrior IDE 4.0 (JDK 1.2) Platform: Windows NT 4.0 **************************** 80 columns wide *********************************/ /** * A more complete Date class that insures invalid dates cannot be * created. If a bad date is given, an InvalidDateException is thrown. * * BUGS: none known **/ class Date { private int day, year; private String month; public final String[ ] months = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}; public final int[ ] monthDays = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; public Date (int day, String month, int year) { this.day = day; this.month = month; this.year = year; if (!yearOK()) throw new InvalidDateException(3); if (!monthOK()) throw new InvalidDateException(2); // must check day last since depends on month and year if (!dayOK()) throw new InvalidDateException(1); } public void setDay (int day) { this.day = day; if (!dayOK()) throw new InvalidDateException(1); } public void setMonth(String month) { this.month = month; if (!monthOK()) throw new InvalidDateException(2); //day may not be valid for new month if (!dayOK()) throw new InvalidDateException(1); } public void setYear (int year) { this.year = year; if (!yearOK()) throw new InvalidDateException(3); //day may not be valid for new year (i.e. leap years) if (!dayOK()) throw new InvalidDateException(1); } public int getDay () { return this.day; } public String getMonth () { return this.month; } public int getYear () { return this.year; } public boolean isLeapYear (int year) { if (year%4 == 0 && year%100 != 0 || year%400 == 0 && year%3600 != 0) return true; return false; } public String toString () { return this.month + " " + this.day + ", " + this.year; } private int findMonth (String month) { for (int i = 0; i < months.length; i++) if (month .equals(months[i])) return i; return -1; } private boolean dayOK () { int i = findMonth(month); if (i == 1 && isLeapYear(this.year) && this.day >= 1 && this.day <= 29) return true; if (i != -1 && this.day >= 1 && this.day <= monthDays[i]) return true; return false; } private boolean monthOK () { if (findMonth(this.month) != -1) return true; return false; } private boolean yearOK () { if (this.year > 0) return true; return false; } }