2-2 Time類的定義(類)
阿新 • • 發佈:2019-02-19
Problem Description
通過本題目的練習可以掌握類與物件的定義;
設計一個時間類Time,私有資料成員有hour(時)、minute(分)、second(秒);
公有成員函式有:setHour(int)設定資料成員hour的值(採用12小時制),非法的輸入預設為12;setMinue(int)設定資料成員minute的值,非法輸入預設為0;setSecond(int)設定資料成員second的值,非法輸入預設為0;setTime(int,int,int)設定時、分、秒三個資料成員的值;showTime()顯示時間物件的值。
在主函式main()中呼叫相應成員函式,使得時間物件的值能從鍵盤接收,並正確顯示。
提示:時、分、秒均按2位數值形式顯示 。
Input
輸入3個整數,用一個空格間隔Output
輸出時、分、秒的值,中間用“:”間隔Sample Input
10 11 12
Sample Output
10:11:12
Hint
輸入
58 23 85
輸出
12:23:00
import java.util.Arrays; import java.util.Scanner; class Time{ int h, m, s; public Time(int h, int m, int s) { this.h = h; this.m = m; this.s = s; } public void seth(){ if(h<0||h>12) { h=12; } } public void setm(){ if(m<0||m>60) { m=0; } } public void sets(){ if(s<0||s>60) { s=0; } } public void show() { System.out.printf("%02d:%02d:%02d\n", h, m, s); } } public class Main { public static void main(String[] args) { Scanner reader = new Scanner(System.in); String s = reader.nextLine(); String str[] = s.split(" "); int h = Integer.parseInt(str[0]); int m = Integer.parseInt(str[1]); int ss = Integer.parseInt(str[2]); Time time = new Time(h,m,ss); time.seth(); time.setm(); time.sets(); time.show(); } }