【问题标题】:Why is nextLine() returning an empty string? [duplicate]为什么 nextLine() 返回一个空字符串? [复制]
【发布时间】:2013-04-09 01:37:53
【问题描述】:

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

我的输入包括一个带有数字的第一行(要读取的行数),一堆带有数据的行和最后一行只有 \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 + "<");
}

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

【问题讨论】:

  • 顺便说一句,第一个数字不是测试数吗?
  • 尝试将 !line.isEmpty() 替换为 line!=null ?
  • 是的,它是测试次数
  • @SamIam 没有
  • 所以,你可以读这个 int x 然后读行 x 次

标签: java


【解决方案1】:

nextInt 不会读取下面的换行符,因此第一个 nextLine (which returns the rest of the current line) 将始终返回一个空字符串。

这应该可行:

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

【讨论】:

  • 该死! .关于为什么会出现这种行为的任何解释?
【解决方案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 + "<");
}

【讨论】:

    【解决方案3】:

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

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

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

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

    【讨论】:

      猜你喜欢
      • 2012-03-15
      • 1970-01-01
      • 2013-05-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-29
      • 2019-03-12
      相关资源
      最近更新 更多