How do I get the scanner to loop until it reads the correct line?

        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 tried to figure this out myself, but I can't get it from looking at other examples, most of them either only accept certain characters or AZ + az

I am trying to get the program to accept male or female input, ignoring case, and if the input is incorrect, repeat "Enter gender:" until the correct value is entered.

+3


source to share


4 answers


You can put a piece of code after a while and check every time. eg:



String gender;
do
{
  System.out.print("Enter Gender ('male' or 'female'): ");
  gender = one.nextLine().toLowercase();
} while(!gender.equals("male") && !gender.equals("female"))

      

+6


source


do {
    System.out.print("Enter Gender (M/F): ");
    gender = one.nextLine();
} while (!gender.equalsIgnoreCase("M") && !gender.equalsIgnoreCase("F"));

      



You can add an if check after the gender assignment to display an invalid message

+2


source


One way to do this is to use an infinite loop and shortcut to exit.
Like this:

//Start 
Scanner one = new Scanner(System.in);
here:
while (true){
System.out.print("Enter Gender: ");
    String str = one.nextLine();
        switch (str.toUpperCase()){
            case "MALE":
                System.out.println("Cool");
                break here;
            case "FEMALE":
                System.out.println("Nice");
                break here;
            default:
                System.out.println("Genders variants: Male/Female");
      }
}

      

+1


source


public class Main {

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    System.out.print("Enter Name: ");
    String name = readValue(scanner, null);
    System.out.print("Enter Date of Birth: ");
    String dateofbirth = readValue(scanner, null);
    System.out.print("Enter Address: ");
    String address = readValue(scanner, null);
    System.out.print("Enter Gender: ");
    String gender = readValue(scanner, createGenderMatcher());
}

private static IMatcher createGenderMatcher() {
    return new IMatcher() {
        @Override
        public boolean isMatch(String value) {
            return "male".equalsIgnoreCase(value) || "female".equalsIgnoreCase(value);
        }
    };
}

private static String readValue(Scanner scanner, IMatcher matcher) {
    String value = null;
    do {
        value = scanner.nextLine();
    } while (matcher != null && !matcher.isMatch(value));
    return value;
}

private interface IMatcher {
    public boolean isMatch(String value);
}

      

+1


source







All Articles