8.2 Time class case study 317 Time jav 1 class declara maintains the t public class Time1 me in 24-hour format. int private int minute o private int second 59 set a new time value using universal time throw an exception if the nute Cint ho our pul nt is inval validate hour minute int second) if (hour 0 minute and second second hour 24 Il minute o II minute 60 Second throw new Illegal \"hour, minute and/or second was out of range\"); this hour hour this minute minute this second second convert to string in universal-time format (HH: MM:SS) public string toUniversalstringo return string format (\"%02d:xo2d: %02d hour minute second) convert to String in standard-time format H MM:SS AM or PM) public string to String return String. format( %d 9602d 9602d %s\" 36 ((hour hour 12) 12 hour 12) 37 minute. second, Chour 12 \"AM\" PM\")) 38 39 class Time 40 end 8.1 Time1 class declaration maintains the time in 24-hour format. Fig. I Default Constructor In this example, class Timel does not declare a constructor, so the compiler supplies a de- ult constructor. Each instance variable implicitly receives the default int value. Instance variables also can be initialized when they\'re declared in the class body, using the same in tialization syntax as with a local variable. Method set Time and Throwing Exceptions that declares three int parameters and Method set Time (I nes 12-25) is a public method value uses them to set the time. Lines 15-16 test each argument to determine whether the is outside the proper range. The hour value must be greater than or equal to 0 and less than
PROGRAM CODE:
Time1.java
package util;
public class Time1 {
private int hour;
private int minute;
private int second;
public void setTime(int hour, int minute, int second)
{
if(hour<0 || hour > 24 || minute<0 || minute > 60 || second <0 || second> 60)
throw new IllegalArgumentException(\"hour, minute and/second out of range\");
this.hour = hour;
this.minute = minute;
this.second = second;
}
public String toUniversalString()
{
return String.format(\"%02d:%02d:%02d\", hour, minute, second);
}
public String toString()
{
return String.format(\"%d:%02d:%02d %s\", ((hour == 0 || hour == 12)?12: hour%12), minute, second ,(hour<12?\"AM\":\"PM\"));
}
}
LabeTime1.java
package util;
public class LabeTime1 {
public static void main(String[] args) {
Time1 breakfastTime = new Time1();
System.out.println(\"Initial breakfast time: \" + breakfastTime);
breakfastTime.setTime(6, 30, 15);
System.out.println(\"Updated breakfast time: \" + breakfastTime);
Time1 dinnerTime = new Time1();
System.out.println(\"Initial dinner time: \" + dinnerTime);
dinnerTime.setTime(19, 25, 05);
System.out.println(\"Updated dinner time: \" + dinnerTime);
}
}
OUTPUT:
Initial breakfast time: 12:00:00 AM
Updated breakfast time: 6:30:15 AM
Initial dinner time: 12:00:00 AM
Updated dinner time: 7:25:05 PM