This code is implemented by Anmol Bhatnagar/CSE Branch/Bhagwan Parshuram Institute of Technology(IP University)
import java.util.*;
public class Watch {
/*
non static data members
*/
int hour;
int minute;
int second;
/*
parameterized constructor to initialize data members
*/
public Watch(int hour, int minute, int second) {
this.hour = hour;
this.minute = minute;
this.second = second;
}
/*
non static method to show the time in 12 hours format
*/
void showTime12F() {
if (hour == 0 && minute >= 0 && minute < 60 && second >= 0 && second < 60) {
System.out.println("12:" + minute + ":" + second + " Midnight");
} else if (hour > 0 && hour < 12 && second >= 0 && second < 60 && minute >= 0 && minute < 60) {
System.out.println(hour + ":" + minute + ":" + second + " AM");
} else if (hour == 12 && second >= 0 && second < 60 && minute >= 0 && minute < 60) {
System.out.println(hour + ":" + minute + ":" + second + " Noon");
} else if (hour > 12 && hour < 24 && second >= 0 && second < 60 && minute >= 0 && minute < 60) {
System.out.println((hour - 12) + ":" + minute + ":" + second + " PM");
} else {
System.out.println("Enter correct time....");
}
}
/*
non static method to show the time in 24 hours format
*/
void showTime24() {
if (hour >=0 && hour < 24 && minute >= 0 && minute < 60 && second >= 0 && second < 60) {
System.out.println(hour + ":" + minute + ":" + second + " Hours");
}
}
public static void main(String[] args) {
/*
object of scanner class created to take input from keyboard
*/
Scanner sc = new Scanner(System.in);
/*
get hour, minutes, and seconds from the keyboard
*/
System.out.print("Enter the hours (0 to 23)->");
int hours = sc.nextInt();
System.out.print("Enter the minutes (0 to 59)->");
int minutes = sc.nextInt();
System.out.print("Enter the seconds (0 to 59)->");
int seconds = sc.nextInt();
/*
create object of Watch and pass values of hours, minutes, and
seconds inside the parameterized constructor
*/
Watch w = new Watch(hours,minutes,seconds);
/*
show a menu
*/
System.out.println("type 1 to show time in 12 hour format");
System.out.println("type 2 to show time in 24 hour format");
/*
take input for choice
*/
int choice = sc.nextInt();
if(choice==1) {
System.out.println("---------------------------------------------");
System.out.print("## Time in 12 hour format is ");
/*
show time in 12 hour format by calling showTime12F() method
*/
w.showTime12F();
System.out.println("---------------------------------------------");
}
else if(choice==2) {
System.out.println("---------------------------------------------");
System.out.print("## Time in 24 hour format is ");
/*
show time in 24 hour format by calling showTime24() method
*/
w.showTime24();
System.out.println("---------------------------------------------");
}
else {
System.out.println("invalid choice");
}
}
}
what will the output If i entered input as
ReplyDeletehour=2
minute=59
second=60