【问题描述】编写程序,把24小时表示法的时间转换为12小时表示法。定义名为TimeFormatException的异常类,如果输入的时间是非法值,比如10:65或者abc,程序应该抛出并处理TimeF

【问题描述】编写程序,把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:30

Time 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");
	}
	

}
  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

肥学

感谢支持

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值