【问题标题】:Java input validation. Does anyone know why that doesn't work?Java 输入验证。有谁知道为什么这不起作用?
【发布时间】:2016-04-07 02:20:43
【问题描述】:

我正在验证所有输入。当我运行程序时,它只接受“ms”或“Ms”或“Mr”或“mr”什么是好的。但是当我输入“先生”时,他将我写错的最后一个单词设置为-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());

【问题讨论】:

    标签: java validation input


    【解决方案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() 更健壮,因为如果用户输入带有“我的标题”之类的空格的内容,它会处理错误

    【讨论】:

    • 使用nextLine会比next
    • 几乎可以肯定,但我试图尽可能地坚持提问者的原始功能。
    • 酷!我喜欢 Stackoverflow。非常感谢@nhouser9
    • @Stiller77 乐于助人 =)
    猜你喜欢
    • 1970-01-01
    • 2015-07-06
    • 2011-05-22
    • 1970-01-01
    • 2012-07-16
    • 1970-01-01
    • 1970-01-01
    • 2011-09-29
    • 1970-01-01
    相关资源
    最近更新 更多