1

I want to validate my user input from Scanner class.

validate it is an integer as well as it must be within the range of [6000, 6999]

        while(!in.hasNext("\\d+")) {
            System.out.println("<Error: Enter numbers only!>");
            System.out.println("Enter postal code :");
            in.nextLine();
        }
        postalCode = in.nextInt();
        in.nextLine();

How do I add in the validation to check if its within the range [6000, 6999]?

EDITED tried this and this is the output. it stop after that

Enter postal code :

d

Error: Enter numbers only!

Enter postal code :

1

Error: Postal code must be betwen 6000-6999 only!

Enter postal code :

1000

            System.out.println("Enter postal code :");
            while(!in.hasNext("\\d+"))
            {
                System.out.println("<Error: Enter numbers only!>");
                System.out.println("Enter postal code :");
                in.nextLine();
            }
            postalCode = in.nextInt();
            while(postalCode < 6000 || postalCode > 6999)
            {
                System.out.println("<Error: Postal code must be betwen 6000-6999 only!>");
                System.out.println("Enter postal code :");
                postalCode = in.nextInt();
                while(!in.hasNext("\\d+"))
                {
                    System.out.println("<Error: Enter numbers only!>");
                    System.out.println("Enter postal code :");
                    in.nextLine();
                }
            }
            in.nextLine();
Ben Yap
  • 199
  • 1
  • 4
  • 10

1 Answers1

2

You need a new while loop. Say postalCode = in.nextInt();, then a new loop while(postalCode < 6000 || postalCode > 6999), lastly prompt the user for a new value.

postalCode = in.nextInt();
while(postalCode < 6000 || postalCode > 6999) {
   System.out.println("Need a number between 6000 and 6999")

   //... revalidate that it is an integer

   postalCode = in.nextInt();
}
Orin
  • 890
  • 5
  • 16