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 = 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.
import java.util.Scanner;
class Adder{
int a[];
public Adder(){
a = new int[2];
}
public void readTime(){
Scanner in = new Scanner(System.in);
System.out.print("Hours: ");
a[0] = Integer.parseInt(in.nextLine());
System.out.print("Minutes: ");
a[1] = Integer.parseInt(in.nextLine());
}
public void addTime(Adder x, Adder y){
this.a[0] = x.a[0] + y.a[0];
this.a[1] = x.a[1] + y.a[1];
this.a[0] += this.a[1] / 60;
this.a[0] %= 24;
this.a[1] %= 60;
}
public void dispTime(){
System.out.print(a[0] + " hour(s) ");
System.out.println(a[1] + " minute(s)");
}
public static void main(String[] args){
Adder x = new Adder();
System.out.println("Time A");
x.readTime();
Adder y = new Adder();
System.out.println("Time B");
y.readTime();
Adder z = new Adder();
z.addTime(x, y);
z.dispTime();
}
}