18

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

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

我有这个输入:

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

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

int numberRegisters;
String line;

Scanner readInput = new Scanner(System.in);

numberRegisters = readInput.nextInt();

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

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

4

3 回答 3

47

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

这应该有效:

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

但我的建议是不要与///等混用nextLinenextInt因为nextDouble任何next试图维护代码的人(包括您自己)可能不知道或忘记了上述内容,因此可能会对上述代码感到有些困惑。

所以我建议:

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

while (!(line = readInput.nextLine()).isEmpty()) {
    System.out.println(line + "<");
}
于 2013-04-16T15:13:48.020 回答
2

我想我以前见过这个问题。我认为你需要添加另一个readInput.nextLine(),否则你只是在结尾之间阅读5\n之后

int numberRegisters;
String line;

Scanner readInput = new Scanner(System.in);

numberRegisters = readInput.nextInt();
readInput.nextLine();

while (!(line = readInput.nextLine()).isEmpty()) {
    System.out.println(line + "<");
}
于 2013-04-16T15:13:55.373 回答
0

实际上它并没有完全回答这个问题(为什么你的代码不起作用),但你可以使用下面的代码。

int n = Integer.parseInt(readInput.readLine());
for(int i = 0; i < n; ++i) {
    String line = readInput().readLine();
    // use line here
}

至于我,它更具可读性,甚至可以在测试用例不正确的极少数情况下节省您的时间(文件末尾有额外信息)

顺便说一句,您似乎参加了一些编程比赛。请注意,扫描仪输入大量数据可能会很慢。您可以考虑使用BufferedReaderwith possible StringTokenizer(此任务中不需要)

于 2013-04-16T15:21:41.563 回答