/************************************* * CS2510 Fall 2011 * Lecture #9.2 * Overloaded Constructor, Exceptions *************************************/ import tester.Tester; // Represents time starting at midnight class Time { int hour; int min; int sec; /** * Template * Fields: * this.hour -- int * this.min -- int * this.sec -- int * Methods: * */ // Our usual constructor to set all values of time Time(int hour, int min, int sec) { this.hour = hour; this.min = min; this.sec = sec; } // Sets hour and min and default sec to 0 Time(int hour, int min) { this(hour,min,0); } // Sets hour and defaults min and sec to 0 Time(int hour) { this(hour,0,0); } } // Represents time from midnight using only seconds class Time2 { private int sec; /** * Template * Fields: * this.hour -- int * Methods: * asString() -- String * addSec(int) -- Time2 */ // Our representation is private to us private Time2(int sec) { this.sec = sec; } // Convert a normal representation to ours Time2(int hour, int min, int sec) { this(hour * 3600 + min*60 + sec); if (hour > 23 || hour < 0) { throw new RuntimeException("Hour is out of bounds"); } else if (min > 59 || min < 0) { throw new RuntimeException("Min is out of bounds"); } else if (sec > 59 || sec < 0) { throw new RuntimeException("Sec is out of bounds"); } } // asString returns the full time representation as a string String asString() { int hour = (sec - (sec % 3600 )) / 3600; int min = (sec/ 60) % 60; int sec = this.sec % 60; return hour + ":" + min + ":" + sec; } // addSec adds some number of seconds (must be less than a minutes-worth) Time2 addSec(int sec) { if(sec > 60) { throw new RuntimeException("Too many seconds!"); } else { return new Time2(this.sec + sec); } } } // Examples and tests of our Time class TimeExamples { Time t11 = new Time(15, 0, 0); Time t12 = new Time(11, 45, 15); Time t13 = new Time(15); Time2 t21 = new Time2(0, 0, 15); Time2 t22 = new Time2(11, 45, 15); String t22s = t22.asString(); // Tests our Time constructor boolean testTime(Tester t) { return t.checkExpect(t11,t13); } // Tests our constructor bounds boolean testTime2(Tester t) { return t.checkConstructorException(new RuntimeException("Hour is out of bounds"), "Time2", 26,45,15); } // Tests addSec bounds boolean testaddSec(Tester t) { return t.checkException(new RuntimeException("Too many seconds!"), t22, "addSec", 70); } }