In: Computer Science
Write a class called Time that represents the time of the day. It has attributes for the hour and minute. The hour value ranges from 0 to 23, where the range 0 to 11 represents a time before noon. The minute value ranges from 0 to 59.
Write a driver program to test your class and call it testTime.. Make sure to test all the methods
Use JavaScript language
class Time{
private int hour,minute;
private boolean isValid(int hour,int minute){
return hour>=0 && hour<24 && minute>=0 && minute<60;
}
public Time(){
this.hour=0;
this.minute=0;
}
public Time(int hour,int minute){
if (isValid(hour,minute)){
this.hour=hour;
this.minute=minute;
}
else
System.out.println("Invalid Time");
}
public Time(int hour,int minute,boolean isAM){
if(hour>0 && hour<=12 && minute>=0 && minute<60){
if(hour==12){
hour=0;
}
if(!isAM){
hour+=12;
}
this.hour=hour;
this.minute=minute;
}
else
System.out.println("Invalid Time");
}
public void setTime(int hour,int minute){
if (isValid(hour,minute)){
this.hour=hour;
this.minute=minute;
}
else
System.out.println("Invalid Time");
}
public void setTime(int hour,int minute,boolean isAM){
if(hour>0 && hour<=12 && minute>=0 && minute<60){
if(hour==12){
hour=0;
}
if(!isAM){
hour+=12;
}
this.hour=hour;
this.minute=minute;
}
else
System.out.println("Invalid Time");
}
public String getTime24(){
String s="";
if(hour<10)
s+='0';
s+=hour;
if(minute<10)
s+=0;
s+=minute;
return s;
}
public String getTime12(){
boolean isAM=true;
int h=hour; //declared a variabe h to store hours so that we can change the hours inside the function and not change the value of the object
if(h==0){
h=12;
}
if(h>12){
h-=12;
isAM=false;
}
String s="";
if(h<10)
s+='0';
s+=h;
s+=':';
if(minute<10)
s+='0';
s+=minute;
if(isAM)
s+=" AM";
else
s+=" PM";
return s;
}
}
public class TestTime
{
public static void main(String[] args) {
Time t=new Time();
t.setTime(16,34);
System.out.println(t.getTime12());
System.out.println(t.getTime24());
t.setTime(4,34,false);
System.out.println(t.getTime12());
System.out.println(t.getTime24());
t=new Time(13,43);
System.out.println(t.getTime24());
System.out.println(t.getTime12());
t=new Time(7,45,true);
System.out.println(t.getTime24());
System.out.println(t.getTime12());
}
}