我正在做一个简单的时钟,它在到达0时回绕(例如00:59 - > 01:00,23:59 - > 00:00)。我此刻陷入困境,无法弄明白。 我必须这样做,只使用' BoundedCounter'中给出的方法。类。
public class Test3 {
public static void main(String[] args) {
BoundedCounter minutes = new BoundedCounter(59, 0);
BoundedCounter hours = new BoundedCounter(23, 0);
int i = 0;
while (i < 70) { //repeats actual time 70 times - just to check if works fine
//put code here
i++;
}
}
}
import java.text.DecimalFormat;
public class BoundedCounter {
private int startValue;
private int upperLimit;
private int value;
public BoundedCounter(int upperLimit, int startValue) {
this.upperLimit = upperLimit;
this.startValue = startValue;
this.value = startValue;
}
public void next() {
value++;
if (value > upperLimit) {
value = 0;
}
}
public String toString() {
DecimalFormat df = new DecimalFormat("#00");
return "" + df.format(value);
}
}
答案 0 :(得分:0)
也许这会有所帮助...显示当前时间:
System.out.println(hours.toString() + ":" + minutes.toString());
增加小时数:hours.next()
增加分钟数:minutes.next()
答案 1 :(得分:0)
一种变体是使用处理程序:
import java.text.DecimalFormat;
public class Test3 {
public static void main(String[] args) {
final BoundedCounter minutes = new BoundedCounter(59, 0);
final BoundedCounter hours = new BoundedCounter(23, 0);
minutes.setOverflow(hours::next);
hours.setOverflow(minutes::reset);
for (int i = 0; i < 70; i++) { //repeats actual time 70 times - just to check if works fine
minutes.next();
System.out.println(hours.toString() + ":" + minutes.toString());
}
}
public static class BoundedCounter {
private int startValue;
private int upperLimit;
private int value;
private Runnable c;
public BoundedCounter(int upperLimit, int startValue) {
this.upperLimit = upperLimit;
this.startValue = startValue;
this.value = startValue;
}
public void reset() {
this.value = startValue;
}
public void setOverflow(final Runnable c) {
this.c = c;
}
public void next() {
if (++value > upperLimit) {
value = 0;
c.run();
}
}
public String toString() {
DecimalFormat df = new DecimalFormat("#00");
return "" + df.format(value);
}
}
}