检查java中的行是否为空?

时间:2013-02-04 15:43:45

标签: java string

  

可能重复:
  How to check that Java String is not all whitespaces

Scanner kb = new Scanner(System.in);
String random;

System.out.print("Enter your word: ");
random = kb.nextLine();

if (random.isEmpty()) {     
    System.out.println("No input detected!");                   
} else {
    System.out.println(random);
}

以上代码不考虑用户何时腾出空间。当用户按空格键并按下回车键时,它仍然会打印空白行。

我该如何解决这个问题?

4 个答案:

答案 0 :(得分:19)

您可以使用String#trim()方法修剪空白,然后进行测试: -

if (random.trim().isEmpty())

答案 1 :(得分:2)

另一个解决方案可能是修剪并且等于空字符串。

if (random.trim().equals("")){       
            System.out.println("No input detected!");                   
}

答案 2 :(得分:1)

另一种解决方案

if (random != null || !random.trim().equals(""))
   <br>System.out.println(random);
<br>else
   <br>System.out.println("No input detected!");

答案 3 :(得分:1)

这就是Apache Commons does it

的方式
public static boolean isBlank(String str) {
    int strLen;
    if (str == null || (strLen = str.length()) == 0) {
        return true;
    }
    for (int i = 0; i < strLen; i++) {
        if ((Character.isWhitespace(str.charAt(i)) == false)) {
            return false;
        }
    }
    return true;
}
相关问题