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;
}
}
操作程序
public class Test04 {
<span style="white-space:pre"> </span>public static void main(String[] args) throws Exception {
<span style="white-space:pre"> </span>Clock c = new Clock();
<span style="white-space:pre"> </span>while(true) {
<span style="white-space:pre"> </span>System.out.println(c.showTime());
<span style="white-space:pre"> </span>c.go();
<span style="white-space:pre"> </span>Thread.sleep(1000);<span style="white-space:pre"> </span>// 让当前程序休眠1秒钟
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>}
}