用户输入验证:日期输入
user input validation: date input
下面有一个方法要求用户通过键盘提供日期,我需要扩展我的代码以验证用户是否确实以 M/d/yyyy 格式输入了数据。
如果没有,请再次要求重复并更正输入数据,我该如何实现?
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());
}
}
}
我认为你很接近,但这是最终解决方案:
从代码中删除了其他逻辑,因为它可以添加。
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);
输出:
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
下面有一个方法要求用户通过键盘提供日期,我需要扩展我的代码以验证用户是否确实以 M/d/yyyy 格式输入了数据。 如果没有,请再次要求重复并更正输入数据,我该如何实现?
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());
}
}
}
我认为你很接近,但这是最终解决方案:
从代码中删除了其他逻辑,因为它可以添加。
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);
输出:
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