Java输入验证。有谁知道为什么不起作用?

时间:2016-04-07 02:20:43

标签: java validation input

我正在验证所有输入。当我运行程序时,它只接受“ms”或“Ms”或“Mr”或“mr”什么是好的。但是当我进入“先生”时,他设置了我写错的最后一个词并将其设置为-title-。然后他跳过了First Name输入,因为他已经设置了正确的“Mr”。该程序无需验证即可运行。为什么它不接受第一个“先生”作为头衔?

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 个答案:

答案 0 :(得分:1)

我怀疑与你如何获得输入有关。试试这个,让我知道它是否有效:

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

只是一个注意事项 - nextLine()可能比next()更强大,因为如果用户输入的内容有“My Title”这样的空格,它会处理错误