用Java 设计一个时钟程序,包含4个类:clock、hour、minute、second,clock类内实现以下三个函数:Time() 显示当前时间,格式HH:mm:SS,tick()每秒执行一次,完成时间经过1秒的功能,set(int HH,int mm,int SS)将时间设置为指定的时分秒,所有的属性都必须为private
时间: 2024-02-03 13:14:34 浏览: 67
设计一个时钟类Clock.zip_c++ 时钟clock_时钟类_时钟类设计_设计CClock类_设计时钟类
下面是一个可能的实现:
Clock.java
```java
public class Clock {
private Hour hour;
private Minute minute;
private Second second;
public Clock() {
this.hour = new Hour();
this.minute = new Minute();
this.second = new Second();
}
public void setTime(int HH, int mm, int SS) {
this.hour.set(HH);
this.minute.set(mm);
this.second.set(SS);
}
public void tick() {
this.second.increment();
if (this.second.get() == 0) {
this.minute.increment();
if (this.minute.get() == 0) {
this.hour.increment();
}
}
}
public String getTime() {
return String.format("%02d:%02d:%02d", this.hour.get(), this.minute.get(), this.second.get());
}
}
```
Hour.java
```java
public class Hour {
private int value;
public Hour() {
this.value = 0;
}
public int get() {
return this.value;
}
public void set(int value) {
this.value = value % 24;
}
public void increment() {
this.value = (this.value + 1) % 24;
}
}
```
Minute.java
```java
public class Minute {
private int value;
public Minute() {
this.value = 0;
}
public int get() {
return this.value;
}
public void set(int value) {
this.value = value % 60;
}
public void increment() {
this.value = (this.value + 1) % 60;
}
}
```
Second.java
```java
public class Second {
private int value;
public Second() {
this.value = 0;
}
public int get() {
return this.value;
}
public void set(int value) {
this.value = value % 60;
}
public void increment() {
this.value = (this.value + 1) % 60;
}
}
```
使用示例:
```java
Clock clock = new Clock();
clock.setTime(23, 59, 59);
for (int i = 0; i < 5; i++) {
clock.tick();
System.out.println(clock.getTime());
}
```
输出:
```
00:00:00
00:00:01
00:00:02
00:00:03
00:00:04
```
阅读全文