【发布时间】:2017-04-17 21:11:02
【问题描述】:
我正在开发一个将 24 小时时间戳转换为 12 小时时间戳的程序。我设法完成了转换并循环它,但我需要在输入验证中编写代码来检查不正确的输入。错误输入的一个示例是:“10:83”或“1):*2”。有人可以告诉我如何使用异常方法来解决这个问题吗?到目前为止,我有这个:
public class conversion {
public static void timeChange() throws Exception {
System.out.println("Enter time in 24hr format");
Scanner sc = new Scanner(System.in);
String input1 = sc.nextLine();
DateFormat df = new SimpleDateFormat("HH:mm");
DateFormat df2 = new SimpleDateFormat ("hh:mm a");
Date date = null;
String timeOutput = null;
date = df.parse(input1);
timeOutput = df2.format(date);
System.out.println("in 12 hour format: " + timeOutput);
decision();
}
public static void decision() throws Exception {
System.out.println("Would you like to enter another time?");
Scanner sc2 = new Scanner(System.in);
String userChoice = sc2.nextLine();
while (userChoice.equalsIgnoreCase("Y")) {
timeChange();
}
System.exit(0);
}
public static void main(String[] args) throws Exception {
timeChange();
}
}
【问题讨论】:
-
一些解析异常示例可在此处的答案中找到:stackoverflow.com/questions/14563011/…
-
请不要使用早已过时且臭名昭著的麻烦
SimpleDateFormat类。今天我们在java.time, the modern Java date and time API 的表现要好得多。
标签: java time time-format