检查java中的行是否为空? [英] Check if line is empty in java?

查看:150
本文介绍了检查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())

这篇关于检查java中的行是否为空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆