Write a program that converts a time from 24-hour notation to 12-hour notation.
ID: 3627429 • Letter: W
Question
Write a program that converts a time from 24-hour notation to 12-hour notation. The following is a sample interaction between the user and the program:Enter time in 24-hour notation:
13:07
That is the same as
1:07 PM
Again? (y/n)
y
Enter time in 24-hour notation:
10:07
That is the same as
10:07 AM
Again? (y/n)
y
Enter time in 24-hour notation:
10:65
There is no such time as 10:65
Try Again:
Enter time in 24-hour notation:
16:05
That is the same as
4:05 PM
Again? (y/n)
n
Define an exception class called TimeFormatException. If the user enters all illegal time, like 10:65, or even gibberish, like 8&*68, you program should throw and handle a TimeFormatException.
Explanation / Answer
please rate - thanks
import java.util.*;
public class timeConvert
{
public static void main(String[] args)
{String time;
int hours,minutes;
Scanner in=new Scanner(System.in);
String []temp;
char ampm;
do
{
System.out.print("Enter time in 24-hour notation: ");
time=in.nextLine();
temp=time.split(":");
hours=Integer.parseInt(temp[0]);
minutes=Integer.parseInt(temp[1]);
if(hours<12)
ampm='A';
else
{ampm='P';
hours-=12;
}
if(hours==0)
hours=12;
System.out.printf("That is the same as %d:%02d %cM ",hours,minutes,ampm);
System.out.print("Again?(y/n) ");
}while(Character.toUpperCase(in.nextLine().charAt(0))=='Y');
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.