在此程序中,您將學(xué)習(xí)計算Kotlin中兩個時間段之間的時差。
class Time(internal var hours: Int, internal var minutes: Int, internal var seconds: Int) fun main(args: Array<String>) { val start = Time(12, 34, 55) val stop = Time(8, 12, 15) val diff: Time diff = difference(start, stop) print("時差: ${start.hours}:${start.minutes}:${start.seconds} - ") print("${stop.hours}:${stop.minutes}:${stop.seconds} ") print("= ${diff.hours}:${diff.minutes}:${diff.seconds}") } fun difference(start: Time, stop: Time): Time { val diff = 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 }
運行該程序時,輸出為:
時差: 12:34:55 - 8:12:15 = 4:22:40
在上面的程序,我們已經(jīng)創(chuàng)建了一個名為 Time 類有三個成員變量hours,minutes和seconds。正如名字所代表的意思,它們分別存儲給定的時間hours,minutes和 seconds。
有一個初始化hours,minutes和seconds的構(gòu)造函數(shù)。
我們還創(chuàng)建了一個靜態(tài)函數(shù)difference,它接受兩個時間變量作為參數(shù),查找時差并將其作為Time類返回。
這是等效的Java代碼:用于計算兩個時間段之間的差的Java程序