英文:
user input validation: date input
问题
以下是你的代码部分,我已经将其翻译好:
private static void extracted2(Doctor l1, Patient p1, List<Schedule> lista) {
Scanner sc2 = new Scanner(System.in);
System.out.println("请提供日期,格式为 M/d/yyyy");
while (true) {
try {
String userinput = sc2.next();
DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("M/d/yyyy");
LocalDate date = LocalDate.parse(userinput, dateFormat);
Schedule g5 = new Schedule(5, l1, p1, date, false, false);
lista.add(g5);
for (Schedule x : lista) {
System.out.println(x);
}
} catch (DateTimeParseException e) {
System.out.println("输入有误,请重新输入正确的日期数据:" + e.getMessage());
}
}
}
注意:我将DataFormatException
更改为DateTimeParseException
,因为在Java中,日期时间解析错误通常会抛出DateTimeParseException
异常。
英文:
I have a method below which asks user to provide date from they keyboard, I need to extend my code to validate if user indeed entered the data in format M/d/yyyy.
If not, ask again to repeat and correct input data, how can I implement that?
private static void extracted2(Doctor l1, Patient p1, List<Schedule> lista) {
Scanner sc2 = new Scanner(System.in);
System.out.println("provide data with format M/d/yyyy");
while (true) {
try {
String userinput = sc2.next();
DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("M/d/yyyy");
LocalDate date = LocalDate.parse(userinput, dateFormat);
Schedule g5 = new Schedule(5, l1, p1, date, false, false);
lista.add(g5);
for (Schedule x : lista) {
System.out.println(x);
}
} catch (DataFormatException e) {
System.out.println("Wrong data " + e.getMessage());
}
}
}
答案1
得分: 0
我认为你已经接近了,但这是最终的解决方案:
从代码中删除了其他逻辑,因为可以随后添加。
Scanner sc2 = new Scanner(System.in);
LocalDate date = null;
boolean isValid;
do {
try {
System.out.println("提供日期格式 M/d/yyyy");
DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("M/d/yyyy");
String userinput = sc2.next();
date = LocalDate.parse(userinput, dateFormat);
isValid = true;
} catch (DateTimeParseException exception) {
isValid = false;
}
} while(!isValid);
System.out.println(date);
输出:
> 提供日期格式 M/d/yyyy
> 333
> 提供日期格式 M/d/yyyy
> 444
> 提供日期格式 M/d/yyyy
> 1/2/2020
> 2020-01-02
英文:
I think you are close but here is the final solution:
Removed other logic from the code since it can be added.
Scanner sc2 = new Scanner(System.in);
LocalDate date = null;
boolean isValid;
do {
try {
System.out.println("Provide date format M/d/yyyy");
DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("M/d/yyyy");
String userinput = sc2.next();
date = LocalDate.parse(userinput, dateFormat);
isValid = true;
} catch (DateTimeParseException exception) {
isValid = false;
}
} while(!isValid);
System.out.println(date);
output:
> Provide date format M/d/yyyy
> 333
> Provide date format M/d/yyyy
> 444
> Provide date format M/d/yyyy
> 1/2/2020
> 2020-01-02
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论