Daniel Daniel - 21 days ago 5
Java Question

Is there any questions on here in relation to only taking "Mr", "Mrs", "Miss" etc at keyboard Input?

This is my code. I only want to accept correct male and female titles. How should I fix this to work because at the moment its not working correctly.

boolean valid = false;
Scanner keyboardIn = new Scanner(System.in);
System.out.println("ENTER ACCOUNT DETAILS: ");
do {
System.out.print("Enter Title: ");
title = keyboardIn.nextLine();
if (title.equals("Mr") || title.equals("Mrs") || title.equals("Ms") || title.equals("Miss")) {
System.out.println("Title set. ");
}
name.setTitle(title);
else {
System.out.println("Error!, You must enter a correct title. ");
}
} while (!valid);

Answer
boolean valid = false;
Scanner keyboardIn = new Scanner(System.in);
System.out.println("ENTER ACCOUNT DETAILS: ");
String title;
do {
    System.out.print("Enter Title: ");
    title = keyboardIn.nextLine();
    if (title.equals("Mr") || title.equals("Mrs") || title.equals("Ms") || title.equals("Miss")) {
        System.out.println("Title set. ");
        name.setTitle(title);
        valid = true;
    } else {
        System.out.println("Error!, You must enter a correct title. ");
    }
} while (!valid);
Comments