简体   繁体   中英

Java input validation. Does anyone know why that doesn't work?

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());

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM