检查java中的行是否为空?

问题描述:


可能重复:

如何检查Java String是不是所有的空格





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);
}

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

The above code doesn't account for when the user makes a space. It'll still print the blank line, when the user does a space and presses enter.

我该如何解决这个问题?

How do I fix this?

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

You can trim the whitespaces using String#trim() method, and then do the test: -

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