【发布时间】:2018-12-05 06:34:49
【问题描述】:
我被要求仅使用 updateDisplay() 方法来更改此时钟显示中小时的格式,一切都可以完美运行,小时可以到达下午 12:59 并使用方法 timeTick() 它到达下午 1:00 但是再次使用 timeTick() 后,它再次进入凌晨 1:01。我该如何解决这个问题?
public class ClockDisplay
{
private NumberDisplay hours;
private NumberDisplay minutes;
private String displayString;
public ClockDisplay()
{
hours = new NumberDisplay(24);
minutes = new NumberDisplay(60);
updateDisplay();
}
public ClockDisplay(int hour, int minute)
{
hours = new NumberDisplay(24);
minutes = new NumberDisplay(60);
setTime(hour, minute);
}
public void timeTick()
{
minutes.increment();
if(minutes.getValue() == 0) { // it just rolled over!
hours.increment();
}
updateDisplay();
}
public void setTime(int hour, int minute)
{
hours.setValue(hour);
minutes.setValue(minute);
updateDisplay();
}
public String getTime()
{
return displayString;
}
private void updateDisplay()
{
int h = hours.getValue()%12;
String format = (hours.getValue()/12 == 0 ? "AM":"PM");
if(h == 0)
{
h = 12;
}
else if(hours.getValue() > 12)
{
hours.setValue(hours.getValue() - 12);
}
displayString = hours.getDisplayValue() + ":" +
minutes.getDisplayValue() + format;
}
}
【问题讨论】:
-
为什么不使用 Java 运行时库中内置的日期/时间格式化方法?
-
请发布完整的包和对象名称和/或您是否使用任何特定的日期库。此外,建议使用可重现该错误的示例可运行程序。
-
因为老师告诉我只能用这种方法改变格式。
-
您只想在小时数小于 12 时打印“AM”,否则打印“PM”。您的线路设置
format没有这样做。 -
所以我需要以另一种方式更改格式。
标签: java time time-format