题目:
实现钟表“时”、“分”的自增
源代码如下:
1.新建Clock.java
public class Clock { private int value = 0; //当前值 //虽然默认零值,但这是一种好习惯 private int limit = 0; //上限,分钟为60,小时为24 public Clock (int limit) { this.limit = limit; } public void increase() {//时钟增加 value++; if(value == limit) {//达到上限后,归零 value = 0; } } public int getValue() {//返回当前小时或分钟 return value; } public static void main(String[] args) { // TODO Auto-generated method stub } }
2.新建Display.java
public class Display { private Clock hour = new Clock(24);//调用类Clock并新建对象hour private Clock minute = new Clock(60);//调用类Clock并新建对象minute public void start() {//计时开始 while(true) { minute.increase(); if( minute.getValue() == 0) { hour.increase(); } System.out.printf("%02d:%02dn",hour.getValue(),minute.getValue()); } } public static void main(String[] args) { // TODO Auto-generated method stub Display display = new Display(); display.start(); } }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)