gpt4 book ai didi

java - 当用户输入无效条目时,通过给出消息允许用户重试来发出错误异常

转载 作者:行者123 更新时间:2023-12-02 09:39:25 25 4
gpt4 key购买 nike

程序假设将用户输入的 24 小时格式时间转换为 12 小时格式,并且输入是否有效。它应该发送一条消息说“输入无效,请重试”,并且程序应该恢复到输入提示。

public class TimeFormatException {


public static void main(String[] args) {

Scanner inputTime = new Scanner(System.in);
String time ;
char stopper;

do {
System.out.println("Enter time in 24-hour notation: ");
time= inputTime.nextLine();
SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm");
DateFormat timeFormatter = new SimpleDateFormat("hh:mm aa");
Date nullTime= null;
String outputTime= null;
timeFormatter = new SimpleDateFormat("hh:mm");
try {
nullTime= timeFormat.parse(time);
outputTime= timeFormatter.format(nullTime);
} catch (ParseException ex) {
ex.printStackTrace();
}
System.out.println("That is the same as "+ outputTime);
System.out.println("Again (y/n)");
Scanner i = new Scanner(System.in);
stopper = i.next().charAt(0);
} while (stopper == 'y' || stopper == 'Y');
}
}

--

java.text.ParseException: Unparseable date: "2"
That is the same as null
Again (y/n)
at java.text.DateFormat.parse(Unknown Source)
at TimeFormatException.main(TimeFormatException.java:39)

最佳答案

您只需在 catch block 内添加 continue 即可。

try {
nullTime= timeFormat.parse(time);
outputTime= timeFormatter.format(nullTime);
} catch (ParseException ex) {
ex.printStackTrace();
continue;
}

这将导致循环从头开始。

您可能希望避免打印堆栈跟踪并改为打印用户友好的消息

try {
nullTime= timeFormat.parse(time);
outputTime= timeFormatter.format(nullTime);
} catch (ParseException ex) {
System.out.println("The time is not in the expected format");
continue;
}

关于java - 当用户输入无效条目时,通过给出消息允许用户重试来发出错误异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57220879/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com