-1

I have a method getIntInput() which returns selection made by a user when called. so now my question is how can I validate user input to be of certain range of option say like 1,2,3,4,5 only anything less or more an exception will be thrown say invalid selection and returns to the top to ask again.

I know this can be achieved using a while or do while but how am I going to go about it.

public static int getIntInput(String prompt){
        Scanner input = new Scanner(System.in);
        int choice = 0;
        System.out.print(prompt);
        System.out.flush();
                   
            try{
                choice = input.nextInt();
            }catch(InputMismatchException e){
                System.out.print("Error only numeric are allowed");
                getIntInput(prompt);
            }
        
        return choice;
    }
Community
  • 1
  • 1
Nabstar
  • 43
  • 1
  • 12
  • 1
    Possible duplicate of [Validate Scanner input on a numeric range](http://stackoverflow.com/questions/30689791/validate-scanner-input-on-a-numeric-range) – cgmb Nov 20 '15 at 01:06

1 Answers1

0

You could raise an exception if the value they input is not in the desired range. However, simply using a do..while loop will handle your requirement of telling them of the invalid input and prompting them again.

As you suggest, use a do..while. Add an if statement to explain why they are being prompted again.

public static int getIntInput(String prompt){
    Scanner input = new Scanner(System.in);
    int choice = 0;
    int min = 1;
    int max = 5;

    do {
        System.out.print(prompt);
        System.out.flush();

        try{
            choice = input.nextInt();
        }catch(InputMismatchException e){
            System.out.print("Error only numeric are allowed");
        }
        if (choice < min || choice > max) {
            System.out.println("Number must be between " + min + " and " + max);
        }
    } while (choice < min || choice > max);

    return choice;
}

Instead of hard coding min and max you can pass them as parameters to getIntInput().

public static int getIntInput(String prompt, int min, int max){
    Scanner input = new Scanner(System.in);
    int choice = 0;

    ...
}
Noah
  • 1,683
  • 14
  • 19