Advertisement
eranseg

Static EX - Clock

Sep 4th, 2019
207
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.90 KB | None | 0 0
  1. //----------------------- Clock.java ------------------------
  2.  
  3. package cls;
  4.  
  5. public class Clock {
  6.  
  7.     //Instance variables
  8.     private int hours;
  9.     private int minutes;
  10.     final int MAX_HOURS = 24;
  11.     final int MAX_MINUTES = 60;
  12.  
  13.     //Static variable
  14.     private static boolean format24 = true;
  15.  
  16.     public Clock(int hours, int minutes) {
  17.         setHours(hours);
  18.         setMinutes(minutes);
  19.     }
  20.  
  21.     public Clock(Clock clock) {
  22.         this.hours = clock.hours;
  23.         this.minutes = clock.minutes;
  24.     }
  25.  
  26.     public int getHours() {
  27.         return hours;
  28.     }
  29.  
  30.     public void setHours(int hours) {
  31.         if(this.minutes > MAX_HOURS) {
  32.             System.out.println("Hours cannot be more then 24");
  33.         } else {
  34.             this.hours = hours;
  35.         }
  36.     }
  37.  
  38.     public int getMinutes() {
  39.         return minutes;
  40.     }
  41.  
  42.     public void setMinutes(int minutes) {
  43.         if(this.minutes > MAX_MINUTES) {
  44.             System.out.println("Minutes cannot be more then 60");
  45.         } else {
  46.             this.minutes = minutes;
  47.         }
  48.     }
  49.  
  50.     public static boolean isFormat24() {
  51.         return format24;
  52.     }
  53.  
  54.     public static void setFormat24(boolean format24) {
  55.         Clock.format24 = format24;
  56.     }
  57.  
  58.     @Override
  59.     public String toString() {
  60.         int h = format24 ? this.hours : this.hours % 12;
  61.         String m = (minutes < 10) ? "0" + this.minutes : "" + this.minutes;
  62.         return (h < 10) ? "0" + h + ":" + m : h + ":" + m;
  63.     }
  64. }
  65.  
  66. //------------------------- Tester class -------------------------------
  67.  
  68. package tester;
  69.  
  70. import cls.Clock;
  71.  
  72. public class ClockTester {
  73.  
  74.     public static void main(String[] args) {
  75.         Clock clock = new Clock(15, 40);
  76.         System.out.println(clock.toString());
  77.         clock.setHours(40);
  78.         Clock.setFormat24(false);
  79.         System.out.println(clock.toString());
  80.     }
  81. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement