Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a scanner to loop until it reads a desired string?

        Scanner one = new Scanner(System.in);
        System.out.print("Enter Name: ");
        name = one.nextLine();
        System.out.print("Enter Date of Birth: ");
        dateofbirth = one.nextLine();
        System.out.print("Enter Address: ");
        address = one.nextLine();  
        System.out.print("Enter Gender: ");
        gender = //not sure what to do now

Hi I've tried to figure this out myself but I can't quite get it from looking at other examples, most are either only accepting certain characters or A-Z+a-z

I'm trying to make the program only accept input of male or female ignoring the case and if the input is wrong to repeat the "Enter Gender:" until a correct value is entered.

like image 736
Purdy Avatar asked Dec 08 '25 06:12

Purdy


1 Answers

You can put the piece of code in a while and validate each time. for instance:

String gender;
do
{
  System.out.print("Enter Gender ('male' or 'female'): ");
  gender = one.nextLine().toLowercase();
} while(!gender.equals("male") && !gender.equals("female"))
like image 132
Daniel Langdon Avatar answered Dec 10 '25 19:12

Daniel Langdon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!