【问题标题】:Java program that asks for user's name and prints it - issue with error message要求输入用户名并将其打印出来的 Java 程序 - 出现错误消息
【发布时间】:2022-02-04 10:04:46
【问题描述】:

我有一个程序会询问用户的姓名并将其打印出来。它可以很好地完成该部分,但是当用户将提示留空并按“Enter”时,它当前存在不打印正确错误消息的问题。

代码:

  //Get User Input
  Scanner sc = new Scanner(System.in);
  System.out.println("What is your name?");

  while (sc.hasNext()) {
     //User Input Variable
     String name = sc.nextLine();
     if (name == null || name.trim().isEmpty()) {
        //Error for empty input, keep asking for valid input
        System.out.print("Please, what is your name?\n");
        sc.next();
     } else {
        //Print name
        System.out.println("Hello " + name + "!");
        break;
     }//End of conditional
  }//End of while loop

当前输出:

What is your name?
<blank space for input>
<Empty Space where error message should be>

理想的输出:

What is your name?
<blank space>
Please, what is your name?

怎么了?

【问题讨论】:

    标签: java string loops if-statement java.util.scanner


    【解决方案1】:

    您唯一需要更改的是while 语句中的条件。 请使用sc.hasNextLine() insted 或sc.hasNext()。然后你会得到想要的输出。这是工作解决方案:

        // Get User Input
        Scanner sc = new Scanner(System.in);
        System.out.println("What is your name?");
    
        while (sc.hasNextLine()) { // here is the difference in the code
            // User Input Variable
            String name = sc.nextLine();
            if (name == null || name.trim().isEmpty()) {
                // Error for empty input, keep asking for valid input
                System.out.print("Please, what is your name?\n");
                sc.hasNextLine(); // here is the difference in the code
            } else {
                // Print name
                System.out.println("Hello " + name + "!");
                break;
            } // End of conditional
        } // End of while loop
    

    【讨论】:

    • 谢谢,它有效!我还发现在错误消息后删除扫描仪方法也可以。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-20
    • 1970-01-01
    • 2012-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多