时钟,有时针,分针,秒针,3个针头共同组成了时间。时钟有两个特性,可以转动,可以表示时间。我们就从这两个特性下手。首先创建一个对象Clock,然后分别用go和showtime,这两个方法来表示转动和表示时间。具体代码如下。
package duhai_10_19;
import java.util.Calendar;
public class Clock {
private int hour;
private int minit;
private int second;
public Clock(){
Calendar cal=Calendar.getInstance();
hour=cal.get(Calendar.HOUR_OF_DAY);
minit=cal.get(Calendar.MINUTE);
second=cal.get(Calendar.SECOND);
}
public void go(){
second++;
if(second==60){
second=0;
minit++;
if(minit==60){
minit=0;
hour++;
if(hour==24)
hour=0;
}
}
}
public void showtime(){
String time="";
if(hour<10){
time=time+"0";
}
time=time+hour+":";
if(minit<10)
time=time+"0";
time=time+minit+":";
if(second<10)
time=time+"0";
time=time+second;
System.out.println(time);
}
}
package duhai_10_19;
public class Test_02 {
public static void main(String[] args) throws Throwable {
Clock p1=new Clock();
while(true){
p1.go();
p1.showtime();
Thread.sleep(1000);
}
}
}