// Author: James D. Skrentny, skrentny@cs.wisc.edu // copyright 2009-2012 all rights reserved // My solutions work from coarse to fine units of time // that is, from year to month to day. // // I've also chosen to test in the order of past, future, and // present. Different orderings are possible. Only when // the current unit of time is in the present, do we test the // next finer unit of time. // WORKS, but can you find any unnecessary if conditions? if (year < YEAR) { System.out.println("Past!"); } else if (year > YEAR) { System.out.println("Future!"); } else if (year == YEAR) { if (month < MONTH) { System.out.println("Past!"); } else if (month > MONTH) { System.out.println("Future!"); } else if (month == MONTH) { if (day < DAY) { System.out.println("Past!"); } else if (day > DAY) { System.out.println("Future!"); } else if (day == DAY) { System.out.println("Present!"); } } } // WORKS and more EFFICIENT. Solution eliminates unnecessary // if conditions. Structure could still be improved since it // still uses 3 if-else-if statements (one for year, month and day). if (year < YEAR) { System.out.println("Past!"); } else if (year > YEAR) { System.out.println("Future!"); } else { // year must be in present if (month < MONTH) { System.out.println("Past!"); } else if (month > MONTH) { System.out.println("Future!"); } else { // year & month both must be in present if (day < DAY) { System.out.println("Past!"); } else if (day > DAY) { System.out.println("Future!"); } else { System.out.println("Present!"); } } } // WORKS, EFFICIENT, and better STRUCTURE. Good solution that uses // 1 if-else-if statement but notice the code redundancy? // Redundancy is a sign of poor structure! We can do better... if (year < YEAR) { System.out.println("Past!"); } else if (year > YEAR) { System.out.println("Future!"); } else if (month < MONTH) { // year in present System.out.println("Past!"); } else if (month > MONTH) { System.out.println("Future!"); } else if (day < DAY) { // year & month in present System.out.println("Past!"); } else if (day > DAY) { System.out.println("Future!"); } else { System.out.println("Present!"); } // WORKS, EFFICIENT, and good STRUCTURE. Excellent solution that // that eliminates the code redundancy above by compounding // the conditions. // Must be careful to include conditions to ensure year and month // are same as present date for logic to work. if ( year < YEAR || year == YEAR && month < MONTH || year == YEAR && month == MONTH && day < DAY) { System.out.println("Past!"); } else if ( year > YEAR || year == YEAR && month > MONTH || year == YEAR && month == MONTH && day > DAY) { System.out.println("Future!"); } else { System.out.println("Present!"); } // Note the compound conditions work without needing extra ()'s! // Why? (hint - review p. 103 and see Appendix B on p. 453)