0

Im on to validate all the inputs. When I run the program it only accepts if there is a "ms" or "Ms" or "Mr" or "mr" what is good. but when I enter "Mr" he sets the last word which I wrote wrong and set it as -title-. Then he skips the First Name input because he set already the right written "Mr" on it. The program works without validation. Why does it not accept the first "Mr" as title?

System.out.println("\nTitle of the student (eg, Mr, Ms): ");
while (!keyboard.hasNext("Mr") && !keyboard.hasNext("Ms") && !keyboard.hasNext("mr") && !keyboard.hasNext("ms")) {
                    {
                        System.out.println("Attention! Title must be Mr or Ms please choose one.");
                       list[i].setTitle(keyboard.next());
                    }

                }

                System.out.println("First name (given name)");
                list[i].setFirstName(keyboard.next());

                System.out.println("A last name (family name/surname)");
                list[i].setFamilyName(keyboard.next());

1 Answer 1

1

I suspect it is an error having to do with how you get your inputs. Try this instead and let me know if it works:

System.out.println("\nTitle of the student (eg, Mr, Ms): ");
String title = keyboard.next();

while (!title.equals("Mr") && !title.equals("Ms") && !title.equals("mr") && !title.equals("ms")) {
{
  System.out.println("Attention! Title must be Mr or Ms please choose one.");

  System.out.println("\nTitle of the student (eg, Mr, Ms): ");
  title = keyboard.next();
}

list[i].setTitle(title);

Just a note - nextLine() is probably more robust than next(), because it handles bugs if the user enters something with a space like "My Title"

Sign up to request clarification or add additional context in comments.

4 Comments

Using nextLine would be better than next
almost certainly true, but i was trying to stick to the asker's original functionality as closely as possible.
Cool!! I love Stackoverflow. Thank you very much @nhouser9
@Stiller77 Happy to help =)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.