In: Computer Science
Consider that time could be internally represented as 3 integers.
MyTime class consists of the following members:
Complete the MyTime class definition and write a main program to test your class in Java.
Output:
Code:
import java.io.*;
class MyTime {
//instance variables
private int hour;
private int minute;
private int second;
//default constructor
MyTime(){
hour = 0;
minute = 0;
second = 0;
}
//parametrized constructors
MyTime(int hour, int minute, int second){
this.setHour(hour);
this.setMinute(minute);
this.setSecond(second);
}
MyTime(int hour, int minute){
this.setHour(hour);
this.setMinute(minute);
second = 0;
}
MyTime(int hour){
this.setHour(hour);
minute = 0;
second = 0;
}
//getters
int getHour(){
return hour;
}
int getMinute(){
return minute;
}
int getSecond(){
return second;
}
//setters
//if there is error in value default value is
set
void setHour(int hour){
if(hour<0 ||
hour>23)
this.hour = 0;
else
this.hour = hour;
}
void setMinute(int minute){
if(minute<0 ||
minute>59)
this.minute = 0;
else
this.minute = minute;
}
void setSecond(int second){
if(second<0 ||
second>59)
this.second = 0;
else
this.second = second;
}
//12-hour Format
String to12HourFormat(){
int h = hour; //modified
hour
boolean am =
(hour>=12) ? false : true; //am or pm
if(hour==0)
h=12;
else
if(hour>12){
h = hour - 12;
}
MyTime newTime = new
MyTime(h, minute, second);
String result =
newTime.toString();
if(am==true)
result += " AM";
else
result += " PM";
return result;
}
public String toString(){
String time = "";
if(hour<10) time +=
"0";
time += hour+":";
if(minute<10) time +=
"0";
time +=
minute+":";
if(second<10) time +=
"0";
time += second;
return time;
}
//main function to test
public static void main (String[] args) {
MyTime ob1 = new
MyTime(5,36,52);
MyTime ob2 = new
MyTime(23,65,46);
MyTime ob3 = new
MyTime(12,56,23);
MyTime ob4 = new
MyTime(0,46,28);
MyTime ob5 = new MyTime(13);
MyTime ob6 = new
MyTime(6,28);
System.out.println(ob1);
System.out.println(ob2.to12HourFormat());
System.out.println(ob3.to12HourFormat());
System.out.println(ob4.to12HourFormat());
System.out.println(ob5);
System.out.println(ob6);
}
}