The purpose of this code is to to implement the time as the number of seconds since midnight. The class should have one data field (an int with the number of seconds since midnight) instead of three. The Driver class will test the Time2 class . This program should ask the user to input the number of hours, minutes, and seconds past midnight, creating a Time2 object and using the mutator methods . The program should then use the toString() method to print out the time.
I am unsure if I could put throw new IllegalArgumentException
into a single statement if I need 3. But I have the code working.
import java.util.Scanner;
public class Driver {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Time2 time = new Time2();
System.out.print("Enter hours:");
int hours = input.nextInt();
System.out.print("Enter minutes:");
int minutes = input.nextInt();
System.out.print("Enter seconds:");
int seconds = input.nextInt();
time.setHour(hours);
time.setMinute(minutes);
time.setSecond(seconds);
time.toString();
}
public static class Time2 {
private int hour;
private int minute;
private int second;
public Time2() {this(0, 0, 0);}
public Time2(int hour) {this(hour, 0, 0);}
public Time2(int hour, int minute) {this(hour, minute, 0);}
public Time2(int hour, int minute, int second) {
if(hour<0||hour>=24)
throw new IllegalArgumentException("hour must be 0-23");
if (minute < 0 || minute >= 60)
throw new IllegalArgumentException("minute must be 0-59");
if (second < 0 || second >= 60)
throw new IllegalArgumentException("second must be 0-59");
this.hour = hour;
this.minute = minute;
this.second = second;
}
public Time2(Time2 time) {this(time.getHour(), time.getMinute(), time.getSecond());}
public void setTime(int hour, int minute, int second) {
if (hour<0||hour>=24)
throw new IllegalArgumentException("hour must be 0-23");
if (minute < 0 || minute >= 60)
throw new IllegalArgumentException("minute must be 0-59");
if (second < 0 || second >= 60)
throw new IllegalArgumentException("second must be 0-59");
this.hour = hour;
this.minute = minute;
this.second = second;
}
public void setHour(int hour) {
if (hour < 0 || hour >= 24)
throw new IllegalArgumentException("hour must be 0-23");
this.hour = hour;
}
public void setMinute(int minute) {
if (minute < 0 && minute >= 60)
throw new IllegalArgumentException("minute must be 0-59");
this.minute = minute;
}
public void setSecond(int second) {
if (second <= 0 || second > 60)
throw new IllegalArgumentException("second must be 0-59");
this.second = second;
}
public int getHour() {return hour;}
public int getMinute() {return minute;}
public int getSecond() {return second;}
public String toUniversalString() {
return String .format( "%02d:%02d:%02d", getHour(), getMinute(), getSecond());
}
public String toString() {
return String .format("%d:%02d:%02d %s",
((getHour() == 0 || getHour() == 12) ? 12 : getHour() % 12), getMinute(),
getSecond(), (getHour() < 12 ? "AM" : "PM"));
}
}
}