简体   繁体   English

要求用户在Java中没有空格的字符串输入

[英]asking for user String input without spaces in java

I need the program to return a message if the user input a string with blank spaces. 如果用户输入带空格的字符串,我需要程序返回一条消息。 for example "this is my house" is not allowed, "thisismyhouse" is allowed. 例如,不允许使用“这是我的房子”,而允许使用“ thisismyhouse”。 right now I use this code to check for blank spaces 现在我用这段代码检查空格

    for(int i = 0; i < blabla.length(); i++) {
        if (blabla.charAt(i) == ' ')
            flag++;
        }
    }
    if (flag != 0) {
        System.out.println("input must not contain spaces");
    }

I wonder if there's a built in function like 'blabla.equals' etc for this purpose? 我想知道是否为此目的有诸如blabla.equals之类的内置函数? or a better way to write this? 还是写这个更好的方法?

Solution 1: 解决方案1:

if(input.contains(" "))
   System.out.println("input must not contain spaces");

Solution 2: 解决方案2:

if(input.indexOf(" ")>=0)
   System.out.println("input must not contain spaces");  

Solution 3: 解决方案3:

You can simply allow the user to enter spaces and remove them yourselves instead: 您可以简单地允许用户输入空格并自行删除它们:

 input = input.replaceAll(" ","");

try 尝试

   if (blabla != null && blabla.contains (" ")) {
      System.out.println("input must not contain spaces");
      return;
   } 

A little search would give you the answer but... There is a method defined in String that returns a boolean value for that purpose already. 稍作搜索就会找到答案,但是...在String 定义了一个方法,该方法已经为此目的返回了布尔值。

if (blabla.contains(" ")) {
System.out.println("input must not contain spaces");
}

You can review the methods of String... 您可以查看String的方法...

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

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