Implement a class Time. A Time object has the instance variables of hour and min
ID: 3840517 • Letter: I
Question
Implement a class Time. A Time object has the instance variables of hour and minute. It also has the methods resetTime (sets the Time to midnight), addMinute (adds a minute to the current time), and printTime (prints the current time).
Note: set the current time in your constructor to 9:00 pm.
The output should be (in military time):
The current time is: 21:00
The reset time is: 00:00
The time in 3 minutes is: 00:03
Remember: you need to account for changing the hour if minute is added to 59.
Explanation / Answer
Time.java
public class Time {
//Declaring instance variables
private int hour;
private int minute;
//Parameterized constructor
public Time(int hour, int minute) {
this.hour = hour;
this.minute = minute;
}
//Zero argumented constructor
public Time() {
super();
}
//this method will make hour and minute value to zero
public void resetTime()
{
hour=0;
minute=0;
}
//This method will add minutes to the current time
public void addMinute(int min)
{
if(minute==59)
{
hour++;
minute+=min-1;
}
else
{
minute+=min;
}
}
//This method will display the time
public void printTime()
{
if(minute<10 && hour<10)
System.out.println("0"+hour+":0"+minute);
else if(minute<10)
System.out.println(hour+":0"+minute);
else if(hour<10)
System.out.println("0"+hour+":"+minute);
else
System.out.println(hour+":"+minute);
}
}
____________________
TestTime.java
import java.util.Scanner;
public class TestTime {
public static void main(String[] args) {
//Declaring variables
int hr,min,addMins;
//Scanner object is used to get the inputs entered by the user
Scanner sc=new Scanner(System.in);
//getting the inputs entered by the user
System.out.print("Enter Hours :");
hr=sc.nextInt();
System.out.print("Enter Minutes :");
min=sc.nextInt();
//creating an Time class object
Time t=new Time(hr, min);
//Displaying the current time
System.out.print("The Current Time is :");
t.printTime();
//calling the reset method
t.resetTime();
System.out.print("The Reset Time is :");
t.printTime();
//getting the minutes user want to add to current time
System.out.print("How many mins you want to add :");
addMins=sc.nextInt();
//Calling the addMinute() method
t.addMinute(addMins);
//Displaying time after adding minutes
System.out.print("The time in "+addMins+" minutes is :");
t.printTime();
}
}
________________________
Output:
Enter Hours :21
Enter Minutes :0
The Current Time is :21:00
The Reset Time is :00:00
How many mins you want to add :3
The time in 3 minutes is :00:03
_____________Thank You
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.