More robust validation

This commit is contained in:
Andrew Regan
2022-01-15 23:34:11 +00:00
parent c256a7b0fb
commit b530057278
2 changed files with 57 additions and 13 deletions

View File

@@ -598,17 +598,33 @@ public class CivilWar {
}
private static String inputString(Predicate<String> validator, String reminder) {
var terminalInput = new Scanner(System.in);
while (true) {
var input = terminalInput.nextLine();
if (validator.test(input)) {
return input;
try {
var input = new Scanner(System.in).nextLine();
if (validator.test(input)) {
return input;
}
} catch (InputMismatchException e) {
// Ignore
}
System.out.println(reminder);
}
}
private static int inputInt(Predicate<Integer> validator, Function<Integer, String> reminder) {
while (true) {
try {
var input = new Scanner(System.in).nextInt();
if (validator.test(input)) {
return input;
}
System.out.println(reminder.apply(input));
} catch (InputMismatchException e) {
System.out.println(reminder.apply(0));
}
}
}
private static boolean isYes(String s) {
if (s == null) {
return false;