简体   繁体   English

如何防止Java扫描仪输入空格

[英]How to prevent Java scanner from inputing spaces

I'm trying to prevent the user from inputting spaces or no values. 我试图防止用户输入空格或没有值。 but nothing works. 但没有任何效果。 Even with no entered values program goes further without printing my error. 即使没有输入值,程序也可以继续运行而不会输出我的错误。 What am I doing wrong? 我究竟做错了什么? my code example 我的代码示例

Scanner nameScan = new Scanner(System.in);
System.out.print("Input your name: ");

String newcomer = nameScan.nextLine();                 
player.setName(newcomer);
String userName = player.getName();
userName = userName.trim();


if (userName.length()==0) {
     System.out.println(" ");
     System.out.println("You have to set up a player name first... ");
     System.out.println(" ");                               
}
else {...

As @11thdimension said, you have to validate the input. 正如@ 11thdimension所说,您必须验证输入。

You can do something like: 您可以执行以下操作:

if (newcomer.isEmpty()) {
    System.out.println("Please write something");
}

Or you can do a while loop and keep asking for a correct input. 或者,您可以进行while循环并继续请求正确的输入。

Your code 您的密码

if(username.length() == 0)

will not check whether the username contains space because space is counted towards the length of the String. 不会检查用户名是否包含空格,因为空格是根据字符串的长度计算的。

To check for empty String input(which may contain space(s)), you can do: 要检查空的字符串输入(可能包含空格),可以执行以下操作:

if("".equals(username.replaceAll("\\s+","")))   //or

if("".equals(username.trim())                   //or

if(username.isEmpty())                   

Further more, you would want to use a do-while loop for validation instead of using an if-statement. 此外,您可能希望使用do-while循环进行验证,而不是使用if语句。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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