这里面用到了一个Java的函数,作用和c++里面sprintf作用一样(带格式转换成字符串)。String.format().
Display类
public class Display {
private int value = 0;
private int limit = 0;
public Display(int limit) {
this.limit = limit;
}
public void increase() {//指针跳一次,进位
value++;
if( value == limit ) {
value = 0;
}
}
public int getValue() {
return value;
}
}
Clock类
public class Clock {
private Display hour;
private Display minute;
private Display second;
public Clock(int hour, int minute, int second) {
this.hour = new Display(hour);
this.minute = new Display(minute);
this.second = new Display(second);
}
public void tick() {//秒针跳一下
second.increase();
if( second.getValue() == 0 ) {
minute.increase();
if( minute.getValue() == 0 ) {
hour.increase();
}
}
}
public String toString() {
return String.format("%02d:%02d:%02d\n", hour.getValue(), minute.getValue(),second.getValue());
}
public void start() {//分针跳一下
while(true) {
minute.increase();
if( minute.getValue() == 0 ) {
hour.increase();
}
System.out.printf("%02d:%02d\n", hour.getValue(), minute.getValue());
}
}
public static void main(String[] args) {
java.util.Scanner in = new java.util.Scanner(System.in);
Clock clock = new Clock(in.nextInt(), in.nextInt(), in.nextInt());
while(true)
{
clock.tick();
System.out.println(clock);
}
}
}