题目:
定义一个时钟类(TimeDemo),属性有:时、分、秒(默认值10时30分),方法有展示当前时间、过1秒,过1分钟,过1小时后的时分秒;定义成员方法分别对时、分、秒进行加减运算,保证运算后时间为真实时间
代码实现如下:
public class TimeDemo { private int hour; //定义小时 private int minute; //定义分钟 private int second; //定义秒 public static void main(String[] args) { TimeDemo timeDemo = new TimeDemo(10, 30, 00); //定义初始时间 timeDemo.display(); timeDemo.addSecond(120); timeDemo.addMinute(120); timeDemo.addHour(48); timeDemo.subSecond(100); timeDemo.subMinute(100); timeDemo.subHour(100); timeDemo.display(); //打印修改后的时间 } public TimeDemo(int x, int y, int z) { this.hour = x; this.minute = y; this.second = z; } public void display() { while (second > 59 || second < 0 || minute > 59 || minute < 0 || hour > 23 || hour < 0) { if (second > 59) { //判断当秒为60时,分要进一位,当分为60时,小时要进一位,当小时为24时,小时要归0 second -= 60; minute++; } if (minute > 59) { minute -= 60; hour++; } if (hour > 23) { hour -= 24; } if (second < 0) { //判断当秒为负数时,向分借位,当分为负数时,向小时借位,当小时为负数时,不断加24直到为正数 second += 60; minute--; } if (minute < 0) { minute += 60; hour--; } if (hour < 0) { hour += 24; } } System.out.println("the time is " + this.hour + ":" + this.minute + ":" + this.second); } public void addHour(int hou) { //加小时 this.hour = this.hour + hou; } public void addSecond(int sec) { //加秒 this.second = this.second + sec; } public void addMinute(int min) { //加分钟 this.minute = this.minute + min; } public void subHour(int hou) { //减小时 this.hour = this.hour - hou; } public void subMinute(int min) { //减分钟 this.minute = this.minute - min; } public void subSecond(int sec) { //减秒 this.second = this.second - sec; } }