8. วัตถุสิ่งของ

The Camtasia Studio video content presented here requires JavaScript to be enabled and the latest version of the Macromedia Flash Player. If you are you using a browser with JavaScript disabled please enable it now. Otherwise, please update your version of the free Flash Player by downloading here.

 
รหัสที่ 8-17  คลาส Time
import java.util.Date;
public class Time {
  private int hour;
  private int minute;
  private int second;

  public Time() {
    Date now = new Date();
    setTime(now.getHours(), now.getMinutes(), now.getSeconds());  
  }   
  public Time(int h, int m, int s) {
    setTime(h, m, s);
  }
  public void setTime(int h, int m, int s) {
    hour = h; minute = m; second = s;
  }
  public int hour() {
    return hour;
  }
  public int minute() {
    return minute;
  }
  public int second() {
    return second;
  }
  public void increment() {  // เพิ่ม 1 วินาที 
    second = (second + 1) % 60;
    if (second == 0) {
      minute = (minute + 1) % 60;
      if (minute == 0) hour = (hour + 1) % 24;
    }
  }
  public String toString() {
    return twoDigits(hour) + ":" +  
           twoDigits(minute) + ":" + twoDigits(second);
  }
  private String twoDigits(int d) {  
    String s = "00" + d;
    return s.substring(s.length()-2, s.length());
  }
}
©2009 S.Prasitjutrakul