为什么nextLine()返回一个空字符串? [英] Why is nextLine() returning an empty string?

查看:221
本文介绍了为什么nextLine()返回一个空字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能是最简单的事情之一,但我没看到我做错了什么。

This is probably one of the easiest things but I'm not seeing what I'm doing wrong.

我的输入包含一个带数字的第一行(要读取的行数),一堆包含数据的行和一行只包含\ n的行。我应该处理这个输入,在最后一行之后,做一些工作。

My input consist of one first line with a number (the number of lines to read), a bunch of lines with data and a final line only with \n. I should process this input and after the last line, do some work.

我有这个输入:

5
test1
test2
test3
test4
test5
      /*this is a \n*/

为了阅读输入,我有这个代码。

And for reading the input I have this code.

int numberRegisters;
String line;

Scanner readInput = new Scanner(System.in);

numberRegisters = readInput.nextInt();

while (!(line = readInput.nextLine()).isEmpty()) {
    System.out.println(line + "<");
}

我的问题是为什么我不打印任何东西?程序读取第一行,然后什么都不做。

My question is why I'm not printing anything? Program reads the first line and then does nothing.

推荐答案

nextInt 不不要读取以下换行符,所以第一个 nextLine 返回当前行的其余部分)将始终返回一个空字符串。

nextInt doesn't read the following new-line character, so the first nextLine (which returns the rest of the current line) will always return an empty string.

这应该有效:

numberRegisters = readInput.nextInt();
readInput.nextLine();
while (!(line = readInput.nextLine()).isEmpty()) {
    System.out.println(line + "<");
}

但我的建议是不要混合 nextLine with nextInt / nextDouble / next /等因为任何试图维护代码(包括你自己)的人都可能没有意识到或忘记了上述代码,所以可能会对上述代码感到有些困惑。

But my advice is not to mix nextLine with nextInt / nextDouble / next / etc. because anyone trying to maintain the code (yourself included) may not be aware of, or have forgotten, the above, so may be somewhat confused by the above code.

所以我建议:

numberRegisters = Integer.parseInt(readInput.nextLine());

while (!(line = readInput.nextLine()).isEmpty()) {
    System.out.println(line + "<");
}

这篇关于为什么nextLine()返回一个空字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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