idastan97

CSCI152 L2 P2

Jan 12th, 2017
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.15 KB | None | 0 0
  1. public class Clock {
  2.     // Fields
  3.     private int hours;
  4.     private int minutes;
  5.     private int seconds;
  6.  
  7.     // Reset method
  8.     public void resetToMidnight() {
  9.         hours = 0; minutes = 0; seconds = 0;
  10.     }
  11.    
  12.     // Constructor
  13.     public Clock(int h, int m, int s) {
  14.         if (h<24 && h>=0 && m<60 && m>=0 && s<60 && s>=0){
  15.             hours = h; minutes = m; seconds = s;
  16.         } else {
  17.             resetToMidnight();
  18.         }
  19.     }
  20.  
  21.     // Check if morning method
  22.     public boolean isMorning() {
  23.         return (hours>=5 && hours<12);
  24.     }
  25.  
  26.     // Advance one second method
  27.     public void tick() {
  28.         seconds++;
  29.         if (seconds >= 60) {
  30.             seconds = 0;
  31.             // need to increment mins, etc.
  32.             minutes++;
  33.             if (minutes>=60){
  34.                 minutes=0;
  35.                 hours++;
  36.                 hours=hours%24;
  37.             }
  38.         }
  39.     }
  40.    
  41.     public String toString(){
  42.         String hs, ms, ss;
  43.         if (hours<10){
  44.             hs="0"+hours;
  45.         } else {
  46.             hs=""+hours;
  47.         }
  48.         if (minutes<10){
  49.             ms="0"+minutes;
  50.         } else {
  51.             ms=""+minutes;
  52.         }
  53.         if (seconds<10){
  54.             ss="0"+seconds;
  55.         } else {
  56.             ss=""+seconds;
  57.         }
  58.         return hs+":"+ms+":"+ss;
  59.     }
  60.    
  61.     public static void main(String[] args){
  62.         Clock time1=new Clock(11, 59, 59);
  63.         Clock time2=new Clock(56, -5, 0);
  64.         System.out.print(time1);
  65.         if (time1.isMorning()){
  66.             System.out.println(" morning.");
  67.         } else {
  68.             System.out.println("not morning");
  69.         }
  70.         System.out.println(time2 + " time 2");
  71.         time1.tick();
  72.         System.out.print(time1);
  73.         if (time1.isMorning()){
  74.             System.out.println(" morning.");
  75.         } else {
  76.             System.out.println(" not morning");
  77.         }
  78.         time1.resetToMidnight();
  79.         System.out.print(time1);
  80.         if (time1.isMorning()){
  81.             System.out.println(" morning.");
  82.         } else {
  83.             System.out.println(" not morning");
  84.         }
  85.     }
  86. }
Advertisement
Add Comment
Please, Sign In to add comment