Advertisements
Advertisements
Question
A class TimeOp has been defined to add any two accepted time periods.
Example: Time A = 6 hours 35 minutes 40 seconds
Time B = 7 hours 45 minutes 30 seconds
Time A + Time B = 14 hours 21minutes 10 seconds
(where 60 minutes = 1 hour and 60 seconds = 1 minute)
The details of the members of the class are given below:
| Data member/instance variable: | |
| arr[] | : integer array to hold three elements (hours, minutes and seconds) |
| Methods/Member functions: | |
| TimeOp() | : default constructor |
| void readTime() | : to accept the elements of the array |
| TimeOp addTime(TimeOp tt) | : to add the time of the parameterised object tt and the current object, to store it in a local object and return it |
| void dispTime() : |
to display the array elements in hours:minutes:seconds format
|
Specify the class TimeOp giving the details of the constructor(), void readTime(), TimeOp addTime(TimeOp) and void dispTime(). Define the main() function to create objects and call the functions accordingly to enable the task.
Code Writing
Advertisements
Solution
import java.util.Scanner;
class TimeOp {
// Data member: array to hold [0] hours, [1] minutes, [2] seconds
int arr[];
// Default constructor
public TimeOp() {
arr = new int[3];
}
// Method to accept elements of the array
public void readTime() {
Scanner sc = new Scanner(System.in);
System.out.print("Enter Hours: ");
arr[0] = sc.nextInt();
System.out.print("Enter Minutes: ");
arr[1] = sc.nextInt();
System.out.print("Enter Seconds: ");
arr[2] = sc.nextInt();
}
// Method to add current object's time with object 'tt'
public TimeOp addTime(TimeOp tt) {
TimeOp res = new TimeOp();
// Add seconds and handle carry for minutes
int totalSeconds = this.arr[2] + tt.arr[2];
res.arr[2] = totalSeconds % 60;
int carryMin = totalSeconds / 60;
// Add minutes and handle carry for hours
int totalMinutes = this.arr[1] + tt.arr[1] + carryMin;
res.arr[1] = totalMinutes % 60;
int carryHrs = totalMinutes / 60;
// Add hours
res.arr[0] = this.arr[0] + tt.arr[0] + carryHrs;
return res;
}
// Method to display time in format
public void dispTime() {
System.out.println(arr[0] + " hours " + arr[1] + " minutes " + arr[2] + " seconds");
}
public static void main(String[] args) {
TimeOp timeA = new TimeOp();
TimeOp timeB = new TimeOp();
System.out.println("Input Time A:");
timeA.readTime();
System.out.println("\nInput Time B:");
timeB.readTime();
// Calculate Sum
TimeOp sum = timeA.addTime(timeB);
System.out.println("\nTotal Time:");
sum.dispTime();
}
}shaalaa.com
Is there an error in this question or solution?
2025-2026 (March) Official Board Paper
