package edu.vtc.cis3720;

import java.util.InputMismatchException;
import java.util.Scanner;

public class InputValidation {

    // This version interprets the next token as an integer and checks high level constraints.
    // If the next token is not an integer an unhandled exception is thrown.
    private static int inputAge1(String prompt, Scanner sc)
    {
        int age;

        while (true) {
            System.out.print(prompt);

            // Check low level format.
            age = sc.nextInt();

            // Check high level constraints.
            if (1 <= age && age <= 150) {
                break;
            }
            else {
                System.out.printf
                        ("Error: %d is not a valid age; expecting value in range 1 .. 150\n", age);
            }
        }
        sc.skip(".*\n");  // Throw away the rest of the line. This approach has its problems.
        return age;
    }


    // This version deals with non-integer tokens by catching the corresponding exception.
    private static int inputAge2(String prompt, Scanner sc)
    {
        int age;

        while (true) {
            System.out.print(prompt);

            try {
                // Check low level format.
                age = sc.nextInt();

                // Check high level constraints.
                if (1 <= age && age <= 150) {
                    sc.skip(".*\n");  // Throw away the rest of the line.
                    break;
                }
                else {
                    System.out.printf
                            ("Error: %d is not a valid age; expecting value in range 1 .. 150.\n", age);
                }
            }
            catch (InputMismatchException ex) {
                System.out.println("Error: Invalid format; expecting an integer.");
                sc.skip(".*\n");  // Throw away the rest of the line.
            }
        }
        return age;
    }


    public static void main(String[] args)
    {
        int someAge;

        Scanner sc = new Scanner(System.in);
        for (int i = 0; i < 10; ++i) {
            someAge = inputAge2("Enter age (" + i + ") in the range 1 .. 150: ", sc);
            System.out.printf("Success! I received: %d\n", someAge);
        }
        sc.close();
    }

}
