【问题描述】编写程序,把24小时表示法的时间转换为12小时表示法。定义名为TimeFormatException的异常类,如果输入的时间是非法值,比如10:65或者abc,程序应该抛出并处理TimeFormatException异常。
提示1:输入一行使用Scanner.nextLine()方法。
提示2:时间格式转换可以使用java.text.SimpleDateFormat类,具体用法自行查看API文档或网上资料。
【输入形式】
【输出形式】
【交互样例】
Enter time in 24-hour notation:
15:20
Time in 12-hour notation is: 03:20 PM
Again?(y/n)
y
Enter time in 24-hour notation:
27:10
TimeFormatException: Invalid Value for Hour!
Try again:
Enter time in 24-hour notation:
16:78
TimeFormatException: Invalid Value for Minute!
Try again:
Enter time in 24-hour notation:
abc
TimeFormatException: Invalid Value for Time!
Try again:
Enter time in 24-hour notation:
6:30Time in 12-hour notation is: 06:30 AM
Again?(y/n)
n
End of program
【样例说明】
【评分标准】
import java.util.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
public class APP {
public static void main(String[]args) throws ParseException {
String s,tmp="y";
SimpleDateFormat time=new SimpleDateFormat("hh:mm");
Scanner sc=new Scanner(System.in);
while(tmp.equals("y")) {
System.out.println("Enter time in 24-hour notation:");
s=sc.nextLine();
try {
String[] arr=s.split(":");
int i=Integer.parseInt(arr[0]),b=Integer.parseInt(arr[1]);
Date date=time.parse(s);
String str=time.format(date);
if(i<13&&b>=0&&b<=60) {
System.out.println("Time in 12-hour notation is: "+str+" AM");
System.out.println("Again?(y/n)");
tmp=sc.nextLine();
}
else if(12<i&&i<=24&&b>=0&&b<=60) {
System.out.println("Time in 12-hour notation is: "+str+" PM");
System.out.println("Again?(y/n)");
tmp=sc.nextLine();}
else {
System.out.println("TimeFormatException: Invalid Value for Hour!\nTry again:");
}
}catch(Exception e) {
System.out.println("TimeFormatException: Invalid Value for Hour!\nTry again:");
}
}
System.out.println("End of program");
}
}