Advertisement
eranseg

Clock

Aug 21st, 2019
2,186
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.12 KB | None | 0 0
  1. /////////////////MAIN CLASS ////////////////////////
  2. public class ClockView {
  3.     public static void main(String[] args) {
  4.         Clock clock = new Clock();
  5.         clock.setHours(5);
  6.         clock.setMinutes(4);
  7.         clock.setSeconds(4);
  8.         clock.show();
  9.         clock.tick();
  10.         clock.tick();
  11.         clock.show();
  12.         clock.reset();
  13.         clock.show();
  14.     }
  15. }
  16.  
  17. ///////////////////// Clock Class ////////////////////////
  18. public class Clock {
  19.  
  20.     // Variables declaration
  21.     private int hours, minutes, seconds;
  22.  
  23.     // Methods
  24.     public int getHours() {
  25.         return hours;
  26.     }
  27.  
  28.     public int getMinutes() {
  29.         return minutes;
  30.     }
  31.  
  32.     public int getSeconds() {
  33.         return seconds;
  34.     }
  35.  
  36.     public boolean setHours(int h) {
  37.         if(h < 0 || h > 23) {
  38.             hours = 0;
  39.             System.out.println("Hours should be between 0 and 59!");
  40.             return false;
  41.         }
  42.         hours = h;
  43.         return true;
  44.     }
  45.  
  46.     public boolean setMinutes(int m) {
  47.         if(m < 0 || m > 59) {
  48.             minutes = 0;
  49.             System.out.println("Minutes should be between 0 and 59!");
  50.             return false;
  51.         }
  52.         minutes = m;
  53.         return true;
  54.     }
  55.  
  56.     public boolean setSeconds(int s) {
  57.         if(s < 0 || s > 59) {
  58.             seconds = 0;
  59.             System.out.println("Seconds should be between 0 and 59!");
  60.             return false;
  61.         }
  62.         seconds = s;
  63.         return true;
  64.     }
  65.  
  66.     public void tick() {
  67.         seconds += 1;
  68.         minutes += seconds / 60;
  69.         hours += minutes / 60;
  70.         seconds %= 60;
  71.         minutes %= 60;
  72.         hours %= 24;
  73.     }
  74.  
  75.     public void show() {
  76.         printElement(hours);
  77.         printElement(minutes);
  78.         if(seconds < 10) {
  79.             System.out.print("0");
  80.         }
  81.         System.out.println(seconds);
  82.     }
  83.  
  84.     public void reset() {
  85.         hours = minutes = seconds = 0;
  86.     }
  87.  
  88.     private void printElement(int n) {
  89.         if(n < 10) {
  90.             System.out.print("0");
  91.         }
  92.         System.out.print(n + ":");
  93.     }
  94. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement