package com.lovo;
import java.util.Calendar;
/**
* 时钟类
* @author 吕懋
*
*/
public class Clock {
private int hour;
// 时
private int minute;
// 分
private int second;
// 秒
/**
* 构造器
*/
public Clock() {
Calendar cal = Calendar.getInstance();
hour = cal.get(11);
minute = cal.get(12);
second = cal.get(13);
}
/**
* 走字
*/
public void go() {
second++;
if(second == 60) {
second = 0;
minute++;
if(minute == 60) {
minute = 0;
hour++;
if(hour == 24) {
hour = 0;
}
}
}
}
/**
* 显示时间
* @return 当前时间的字符串
*/
public String showTime() {
String time = "";
if(hour < 10) {
time += "0";
}
time += hour + ":";
if(minute < 10) {
time += "0";
}
time += minute + ":";
if(second < 10) {
time += "0";
}
time += second;
return time;
}
}
测试
package com.lovo;public class Test04 {
public static void main(String[] args) throws Exception {
Clock c = new Clock();
while(true) {
System.out.println(c.showTime());
c.go();
Thread.sleep(1000); // 让当前程序休眠1秒钟
}
}
}