Answer:
The program to this question can be given as follows:
Program:
import java.util.*; //import package
class Time //defining class Time
{
int hours,minutes,seconds; //defining integer variable
Time(int hours, int minutes, int seconds)//defining parameterized constructor
{
//using this keyword
this.hours = hours; //holding a value
this.minutes = minutes; //holding a value
this.seconds = seconds; //holding a value
}
int getHours() //defining method getHours
{
return hours; //return value
}
void setHours(int hours) //defining method setHours
{
this.hours = hours; //holing a value in hours variable
}
int getMinutes() //defining method getMinutes
{
return minutes; //return value
}
void setMinutes(int minutes) //defining method setMinutes
{
this.minutes = minutes; //holing a value in minutes variable
}
int getSeconds() //defining method getSeconds
{
return seconds; //return value
}
void setSeconds(int seconds) //defining method setSeconds
{
this.seconds = seconds; //holing a value in seconds variable
}
void displayTime() //defining method displayTime
{
System.out.println(hours + ":" + minutes + ":" + seconds); //print the value
}
}
public class TimeTest //defining class TimeTest
{
public static void main(String[] args) //defining main method
{
int h, m, s; //defining integer variable
Scanner ob1= new Scanner(System.in); //creating Scanner class Object
System.out.print("Enter number of hours: "); //message
h = ob1.nextInt(); //input value by user
System.out.print("Enter number of minutes: "); //message
m = ob1.nextInt(); //input value by user
System.out.print("Enter number of seconds: "); //message
s = ob1.nextInt(); //input value by user
//using conditional statement
if(h < 0 || m < 0 || s < 0 || h > 23 || m > 59 || s > 59) //checking value
{
System.out.println("Invalid input. please Try again!"); //message
}
else
{
Time t = new Time(h, m, s); //creating Time class object
t.displayTime(); //calling displayTime method
}
}
}
Output:
Enter number of hours: 12
Enter number of minutes: 22
Enter number of seconds: 50
12:22:50
Step-by-step explanation:
In the above java code, two class "Time and TimeTest" is defined, in the time class three integer variable "hours, minutes, and seconds" is defined, which use in the parameterized constructor with this keyword to hold constructor parameters value.
- In this class, the getter and setter method is used for variable, in which getter method is used to get value by user and setter method sets its value in this class a method "displayTime" is defined, that doesn't return any value but it will print the time in the given format.
- Then the main class "TimeTest" is defined, in this class main method is declared, that creates the scanner class object for user input and create the "Time" class object, that accepts user-input values and check values by using conditional statement and call the "displayTime" function.