PRASHNIKAप्रश्निका
‹ Back to the paper

A class Adder has been defined to add any two accepted time. Example: Time A - 6 hours 35 minutes…

Computer Science201710 marksProgram
A class Adder has been defined to add any two accepted time. Example: Time A - 6 hours 35 minutes Time B - 7 hours 45 minutes Their sum is - 14 hours 20 minutes ( where 60 minutes = 1 hour) The details of the members of the class are given below: Class name : Adder Data member/instance variable: a[ ] : integer array to hold two elements (hours and minutes) Member functions/methods: Adder( ) : constructor to assign 0 to the array elements void readtime( ) : to enter the elements of the array void addtime( Adder X, Adder Y) : adds the time of the two parameterized objects X and Y and stores the sum in the current calling object void disptime( ) : displays the array elements with an appropriate message (i.e. hours = and minutes = ) Specify the class Adder giving details of the constructor( ), void readtime( ), void addtime(Adder, Adder) and void disptime( ). Define the main( ) function to create objects and call the functions accordingly to enable the task.

Answer

Answer

AI
import java.util.Scanner;

class Adder
{
    int a[] = new int[2];   // a[0] = hours, a[1] = minutes

    Adder()
    {
        a[0] = 0;
        a[1] = 0;
    }

    void readtime()
    {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter hours: ");
        a[0] = sc.nextInt();
        System.out.print("Enter minutes: ");
        a[1] = sc.nextInt();
    }

    void addtime(Adder X, Adder Y)
    {
        a[1] = X.a[1] + Y.a[1];
        a[0] = X.a[0] + Y.a[0] + a[1] / 60;   // carry of minutes goes to hours
        a[1] = a[1] % 60;
    }

    void disptime()
    {
        System.out.println("hours = " + a[0] + " and minutes = " + a[1]);
    }

    public static void main(String args[])
    {
        Adder A = new Adder();
        Adder B = new Adder();
        Adder C = new Adder();
        System.out.println("Enter Time A:");
        A.readtime();
        System.out.println("Enter Time B:");
        B.readtime();
        C.addtime(A, B);
        System.out.println("Sum of the two times:");
        C.disptime();
    }
}
Explanation: addtime() adds the minutes of X and Y, adds the hours plus the carry (minutes / 60) and keeps the remainder (minutes % 60) as the minutes of the calling object. Tested by running: 6 h 35 min + 7 h 45 min gives hours = 14 and minutes = 20.
Arrays, StringsObjects

From ISC 2017 Computer Science Paper 1, question 8.