1

I'm trying to tell the user to input an integer in 1-90 range, how do I re-ask them to type a valid input and range if they typed in an invalid one?

package encapsulation;

import java.util.ArrayList;
import java.util.Scanner;

public class Assignment2 {

    public static void showMenu() {
        System.out.println("+=====================+");
        System.out.println("+Menu                 +");
        System.out.println("+=====================+");
        System.out.println("+1. Add Sick Pet      +");
        System.out.println("+2. View Sick List    +");
        System.out.println("+3. Update Pet Health +");
        System.out.println("+4. Treat Pet         +");
        System.out.println("+5. Exit Program      +");
        System.out.println("+=====================+");
        System.out.printf("Choice >> ");

    }

    public static void main(String[] args) {

        Scanner scan = new Scanner(System.in);

        ArrayList<Integer> petHealth = new ArrayList<Integer>();
        ArrayList<String> petName = new ArrayList<String>();
        ArrayList<String> petType = new ArrayList<String>();

        while(true) {
            showMenu();
            int menu = scan.nextInt();
            if (menu == 1) {
                System.out.printf("Input pet health [1-90]: "); //this printf
                int health = scan.nextInt();
                //if health is not an integer, or not in range (1-90), repeat the printf and scan again until correct
            }
        }

    }

}

I tried to use a try catch statement, but if the user typed an invalid input, the program will stop instead of asking again.

Example of a repeating scan if previous input is invalid:

Input pet health [1-90]: -1 //invalid, repeat
Input pet health [1-90]: a //invalid, repeat
Input pet health [1-90]: 91 //invalid, repeat
Input pet health [1-90]: 5 //valid, continue
baronoke
  • 57
  • 6

0 Answers0