Tomek Młynarski :
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());
}
}
}
dkb :
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
Guess you like
Origin http://10.200.1.11:23101/article/api/json?id=409701&siteId=1