I am really having trouble with this 2 part question. I can\'t seem to get it to
ID: 3644150 • Letter: I
Question
I am really having trouble with this 2 part question. I can't seem to get it to work.Part 1
Consider a class Time that represents a time of 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.
a. Write a default constructor that initializes the time to 0 hours, 0 minutes.
b. Write a private method isValid(hour, minute) that returns true if the
given hour and minute values are in the appropriate range.
c. Write a method setTime(hour, minute) that sets the time if the given
values are valid.
Part 2
Complete and fully test the class Time that Exercise 2 describes. Add two
more constructors that are analogous to the setTime methods described in
Parts c and d of Exercise 2. Also include the following methods:
getTime24 returns a string that gives the time in 24-hour notation hhmm.
For example, if the hour value is 7 and the minute value is 25, return
"0725". If the hour value is 0 and the minute value is 5, return "0005".
If the hour value is 15 and the minute value is 30, return "1530".
getTime12 returns a string that gives the time in 12-hour notation h:mm
xx. For example, if the hour value is 7 and the minute value is 25, return
"7:25 am". If the hour value is 0 and the minute value is 5, return
"12:05 am". If the hour value is 15 and the minute value is 30, return
"3:30 pm".
Explanation / Answer
Please rate...
public class Time
{
private int hour;
private int minute;
Time()
{
hour=0;
minute=0;
}
private boolean isValid(int h,int m)
{
if(h>=0 && h<=23 && m>=0 && m<=59)return true;
else return false;
}
public void setTime(int h,int m)
{
if(isValid(h,m))
{
hour=h;
minute=m;
}
}
public String getTime24()
{
String t;
if(hour<=9)t="0"+hour;
else t=""+hour;
if(minute<=9)t=t+"0"+minute;
else t=t+minute;
return t;
}
public String getTime12()
{
String t;
if(hour>12)t=""+(hour-12)+":";
else t=""+hour+":";
if(minute<=9)t=t+"0"+minute;
else t=t+minute;
if(hour<12)t=t+" am";
else t=t+" pm";
return t;
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.