Novice here, please take it easy on me...
What is the Java/OOP way to cleanup the input validation logic I have below? The check to ensure an int has been entered is executed multiple times throughout the main method. It feels dirty duplicating input validation lines multiple times. Notice the question changes for each input.
I assume one solution is to pass keyInput and the question (a String) to a method that completes the validation and returns keyInput.nextInt when the input is good.
What would a non-novice do?
Thank you.
public static void main(String[] args) {
Scanner keyInput = new Scanner(System.in);
int level = 0;
boolean badInput = true;
int answer = 0;
while (badInput) {
System.out.print("Enter a level between 1 and 4: ");
if (!keyInput.hasNextInt()) {
System.out.println("*** Input is not an integer! ***\n");
keyInput.next();
continue;
}
level = keyInput.nextInt();
if (level < 1 || level > 5) {
System.out.println("*** Number is not between 1 and 4! ***\n");
continue;
}
badInput = false;
}
MathChallenge game = new MathChallenge(level);
badInput = true;
while (badInput) {
System.out.print("Enter the sum of " + game.getArray() + ": ");
if (!keyInput.hasNextInt()) {
System.out.println("*** Input is not an integer! ***\n");
keyInput.next();
continue;
}
...
Scannerhas quirks and makes it difficult to write code that works in all cases. I personally would never use it. Instead I'd read entire lines and then parse out what I needed.