Advertisement
Guest User

Untitled

a guest
Oct 22nd, 2019
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.95 KB | None | 0 0
  1. public class Time {
  2.     private final int seconds;
  3.    
  4.     public Time(int h, int m, int s) {
  5.         seconds = h * 3600 + m * 60 + s;
  6.     }
  7.    
  8.     public Time(String time) {
  9.         String[] parts = time.split(":");
  10.         int total = 0;
  11.         int f = 1;
  12.         for(int i = parts.length-1; i >= 0; i--) {
  13.             total += Integer.parseInt(parts[i])*f;
  14.             f *= 60;
  15.         }
  16.         seconds = total;
  17.     }
  18.    
  19.     public int getHours() {
  20.         return seconds / 3600;
  21.     }
  22.    
  23.     public int getMinutes() {
  24.         return seconds % 3600 / 60;
  25.     }
  26.    
  27.     public int getSeconds() {
  28.         return seconds % 3600 % 60;
  29.     }
  30.    
  31.     @Override
  32.     public String toString() {
  33.         return getHours() + ":" + getMinutes() + ":" + getSeconds();
  34.        
  35.     }
  36.    
  37.     public Time add(Time t) {
  38.         return new Time(0, 0, seconds + t.seconds);
  39.     }
  40.    
  41.     public static void main(String[] args) {
  42.         Time t1 = new Time(1, 20, 5);
  43.         Time t2 = new Time("45:0");
  44.        
  45.         System.out.println(t1);
  46.         System.out.println(t2);
  47.         Time t3 = t1.add(t2);
  48.         System.out.println(t3);
  49.     }
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement