Java 询问用户名并打印它的程序 - 出现错误消息
Java program that asks for user's name and prints it - issue with error message
我有一个程序可以询问用户的姓名并将其打印出来。它可以很好地完成该部分,但目前存在的问题是,当用户将提示留空并按“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?
怎么了?
您唯一需要更改的是 while
语句中的条件。
请使用 sc.hasNextLine()
而不是 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
我有一个程序可以询问用户的姓名并将其打印出来。它可以很好地完成该部分,但目前存在的问题是,当用户将提示留空并按“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?
怎么了?
您唯一需要更改的是 while
语句中的条件。
请使用 sc.hasNextLine()
而不是 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