8.2 Time Class case study 317 l Fig. 8.1: Timel java 2 Timel class declaration m
ID: 3792184 • Letter: 8
Question
8.2 Time Class case study 317 l Fig. 8.1: Timel java 2 Timel class declaration maintains the time in 24-hour format. 4 public class Timel 6 private int hour 0 23 7 private int minute 0 59 s private int second 0 59 set a new time value using universal time throw an I l exception if the hour minute or second is invalid public void setTime (int hour, int minute, int second) 13 validate hour, minute and second if (hour 0 II hour 24 Il minute 0 II minute 60 il 15 second 0 II second 60) throw new IllegalArgumentException( "hour, minute and/or second was out of range"); 20 this hour hour 22 this minute minute this second m second; 26 27 convert to String in universal-time format (HH: MM: SS) 28 public String toUniversaistringo return String.format("x02d x02d NO2d', hour minute second) 30 33 convert to String in standard-time format (H:MM:ss AM or PM) 34 public String tostringo return string format %d:%02d 302d 36 (Chour 0 ll hour 12) 12 hour x 12) minute second, Chour 12 AM "PM'i)); 40 end class Tittel Fig. 8.1 l Timel class declaration maintains the time in 24-hour formatExplanation / Answer
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) {
//breakfast Time object creation and instantiation
Time1 breakfastTime = new Time1();
System.out.println("Initial breakfast time: " + breakfastTime);
breakfastTime.setTime(6, 30, 15);
System.out.println("Updated breakfast time: " + breakfastTime);
//dinnerTime object creation and instantiation
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
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.