1

我的申请有问题。我希望应用程序检测到如果用户没有为字符串输入任何值(换句话说,在被要求输入内容后只需按 Enter),应用程序就会询问他/她是否希望退出程序。
我做对了吗?

words = s.nextLine();   
if (words.equals(null)) {
4

5 回答 5

7

不,你做的不对。

nextLine()如果用户只是点击返回,将返回一个字符串。据我所知,它永远不会回来null。如果已经到达输入的末尾,它将抛出NoSuchElementException(与在BufferedReader.readLine()这种情况下返回 null 不同)。所以你要:

if (words.equals(""))

或者

if (words.length() == 0)

或者

if (words.isEmpty())

...hasNextLine()如果您想先检测输入的结束,请使用。

于 2012-11-27T11:19:21.993 回答
5

不你不是。

如果用户只是按下回车键,你会得到一个空字符串,而不是null. 这可以检查为

if(words.equals(""))

如果有空格,这将失败。在这种情况下

if(words.trim().equals(""))

应该管用。

于 2012-11-27T11:21:17.837 回答
4

null 不正确,因为你得到的是一个空字符串:

使用: words.isEmpty()words.equals("")words.length()==0

于 2012-11-27T11:21:09.330 回答
0

这应该有效:

if (words == null || words.length() == 0) {
于 2012-11-27T11:19:13.430 回答
0

返回的字符串不是空的,它只是一个空字符串。

words.equals("");

应该是正确的

于 2012-11-27T11:23:44.610 回答