Thursday, 17 October 2013

Additon or Substraction of two times. An object oriented approach.

import java.io.*;
class Times
{
    int h,m,s;
    Times(int x,int y,int z)
    {
        h=x;m=y;s=z;
    }
    Times SubTime(Times a,Times b)
    {
        Times c=new Times(0,0,0);
        c.s=a.s-b.s;
        if(c.s<0)
        {
            c.s=c.s+60;
            c.m=-1;
        }
        c.m=a.m-b.m+c.m;
        if(c.m<0)
        {
            c.m=c.m+60;
            c.h=-1;
        }
        c.h=a.h-b.h+c.h;
        return c;
    }
    Times AddTime(Times a,Times b)
    {
        Times c=new Times(0,0,0);
        c.s=a.s+b.s;
        if(c.s>=60)
        {
            c.s=c.s-60;
            c.m=+1;
        }
        c.m=a.m+b.m+c.m;
        if(c.m>=60)
        {
            c.m=c.m-60;
            c.h=+1;
        }
        c.h=a.h+b.h+c.h;
        return c;
    }
    public static void main(String arg[])throws IOException
    {
        Times call=new Times(0,0,0),a=new Times(0,0,0),b=new Times(0,0,0),c=new Times(0,0,0);
        BufferedReader X=new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Enter Time A in 24-hr format");
        int p=Integer.parseInt(X.readLine());
        int q=Integer.parseInt(X.readLine());
        int r=Integer.parseInt(X.readLine());
        if(p>24||q>60||r>60)
        System.out.println("Invalid Time");
        else
        {
            a=new Times(p,q,r);
            System.out.println("Enter Time B in 24-hr format such that A>B");
            p=Integer.parseInt(X.readLine());
            q=Integer.parseInt(X.readLine());
            r=Integer.parseInt(X.readLine());
            if(p>24||q>60||r>60)
            System.out.println("Invalid Time");
            else
            {
                b=new Times(p,q,r);
                System.out.println("\nTime A");
                a.display();
                System.out.println("\nTime B");
                b.display();
                System.out.println("\nAfter adding, new Time is");
                c=call.AddTime(a,b);
                c.display();
                System.out.println("\nAfter substracting, new Time is");
                c=call.SubTime(a,b);
                c.display();
            }
        }
    }
    void display()
    {
        System.out.println(h+" hours "+m+" minutes "+s+" seconds");
    }
}

No comments:

Post a Comment