在此程序中,您將學(xué)習(xí)計算Java中兩個時間段之間的時差。
public class Time { int seconds; int minutes; int hours; public Time(int hours, int minutes, int seconds) { this.hours = hours; this.minutes = minutes; this.seconds = seconds; } public static void main(String[] args) { Time start = new Time(12, 34, 55), stop = new Time(8, 12, 15), diff; diff = difference(start, stop); System.out.printf("TIME DIFFERENCE: %d:%d:%d - ", start.hours, start.minutes, start.seconds); System.out.printf("%d:%d:%d ", stop.hours, stop.minutes, stop.seconds); System.out.printf("= %d:%d:%d\n", diff.hours, diff.minutes, diff.seconds); } public static Time difference(Time start, Time stop) { Time diff = new Time(0, 0, 0); if(stop.seconds > start.seconds){ --start.minutes; start.seconds += 60; } diff.seconds = start.seconds - stop.seconds; if(stop.minutes > start.minutes){ --start.hours; start.minutes += 60; } diff.minutes = start.minutes - stop.minutes; diff.hours = start.hours - stop.hours; return(diff); } }
運行該程序時,輸出為:
TIME DIFFERENCE: 12:34:55 - 8:12:15 = 4:22:40
在上面的程序,我們已經(jīng)創(chuàng)建了一個名為Time類有三個成員變量hours,minutes和seconds。正如名字所暗示的,它們分別給定的時間存儲hours,minutes和seconds。
Time類具有一個構(gòu)造函數(shù),用于初始化hours,minutes和seconds。
我們還創(chuàng)建了一個靜態(tài)函數(shù)difference,它接受兩個時間變量作為參數(shù),查找差異并將其作為Time類返回