定义名为MyTime类添加以下方法: 定义名为MyTime的类,其中有三个整型成员变最:时(hour),分(minute)。秒(secand),为了保证数据的安全性,这三个成员变最应声明为私有。为MyTime类定文 addSecond(int sec)addMinute(int min),addHour(int hou) subSecond(int sec)、subMinute(int min)、subHour(int hou)分别对时、分、秒进行加减运算。 创建测试类,分别对时分秒进行加减,显示时间并给出时间是否是合法的时间。
时间: 2024-02-23 08:58:13 浏览: 176
好的,以下是代码示例:
```java
public class MyTime {
private int hour;
private int minute;
private int second;
public MyTime(int hour, int minute, int second) {
this.hour = hour;
this.minute = minute;
this.second = second;
}
public void addSecond(int sec) {
int totalSec = this.second + sec;
this.second = totalSec % 60;
int carry = totalSec / 60;
addMinute(carry);
}
public void addMinute(int min) {
int totalMin = this.minute + min;
this.minute = totalMin % 60;
int carry = totalMin / 60;
addHour(carry);
}
public void addHour(int hou) {
this.hour = (this.hour + hou) % 24;
}
public void subSecond(int sec) {
int totalSec = this.second - sec;
if (totalSec < 0) {
totalSec += 60;
subMinute(1);
}
this.second = totalSec;
}
public void subMinute(int min) {
int totalMin = this.minute - min;
if (totalMin < 0) {
totalMin += 60;
subHour(1);
}
this.minute = totalMin;
}
public void subHour(int hou) {
int totalHour = this.hour - hou;
if (totalHour < 0) {
totalHour += 24;
}
this.hour = totalHour;
}
public String toString() {
return String.format("%02d:%02d:%02d", hour, minute, second);
}
}
```
接下来是测试类:
```java
public class TestMyTime {
public static void main(String[] args) {
MyTime time = new MyTime(12, 30, 45);
System.out.println("初始时间:" + time);
time.addSecond(15);
System.out.println("加15秒后:" + time);
time.addMinute(40);
System.out.println("加40分钟后:" + time);
time.addHour(2);
System.out.println("加2小时后:" + time);
time.subSecond(10);
System.out.println("减10秒后:" + time);
time.subMinute(50);
System.out.println("减50分钟后:" + time);
time.subHour(4);
System.out.println("减4小时后:" + time);
}
}
```
运行结果为:
```
初始时间:12:30:45
加15秒后:12:31:00
加40分钟后:13:11:00
加2小时后:15:11:00
减10秒后:15:10:50
减50分钟后:14:20:50
减4小时后:10:20:50
```
阅读全文