Okay so I have a clock class which is initially set as a 24 hour clock but I have to have the clock display as a 12 hour clock using only this method! I have tried for hours but have fallen short! Please help. Make the clock display the time as a 12 hour clock (hh:mm:ss AM/PM). Use abstraction - don’t change anything but the updateDisplay() method. The clock can use military time "under the covers"; it just needs to return the proper string when getTime() is called.
private void updateDisplay()
{
String AM = "AM";
String PM = "PM";
if(hours.getValue() == 0) {
hours.setValue(hours.getValue() + 12);
PM = "";
}
else if(hours.getValue() == 1 < hours.getValue() && hours.getValue() < 11) {
PM = "";
}
else if(hours.getValue() == 12) {
AM = "";
}
else if(hours.getValue() == 13 > 24) {
hours.setValue(hours.getValue() - 12);
AM = "";
}
displayString = hours.getDisplayValue() + ":" +
minutes.getDisplayValue() + ":" +
seconds.getDisplayValue() + PM + AM;
}
A 24 Hour clock, H, runs from 0<=H<=23. If H div 12
is 0, then AM, else PM. Then the 12 Hour clock, h, is H mod 12
unless that value is 0, in which case h = 12.
You shouldn't be changing the value (hours.setValue(...)
) in your display code, nor do you need to convert to seconds.
I think the issue with your code is just a syntax problem in the first conditional statement.
... if(hours.getValue() == 1 < hours.getValue() ... // This is wrong
You are comparing the value of hours to 1, and then the result of the comparison to hours. This won't compile in java, because bools are incomparable to ints.
Note: When I say div
, I mean an integer division (i.e. truncated /
operator in Java), and when I say mod
I mean an integer modulus (%
operator in Java).
Update: All you need to do is convert your 24 hour value hours.getValue()
to the 12 Hour equivalent for display. Something along the lines of:
// Not correct Java!
string meridianNess = (hours.getValue()/12==0?"AM":"PM");
int h = hours.getValue()%12;
if (h==0) h = 12;
System.out.print(h+":"+new NumberFormat("00").format(minutes.getValue())+":"+
new NumberFormat("00").format(seconds.getValue())+" "+meridianNess);