Java下一行没有令牌,但应该有?

时间:2015-01-16 23:07:24

标签: java input java.util.scanner token

public static void flipLines(Scanner input) {
    int i = 0;
    while (input.hasNextLine()) {
        String ignore = input.nextLine();
        if (i >= 0) {
            System.out.println(input.nextLine());
            System.out.println(ignore);
        } i++;
    }
}

我有这个,我正试图从扫描仪的输入中翻转线条。我得到一个令牌错误,表示只在最后一行读取此文本时没有行。下面是完全翻转时应该看起来的样子,但是你可以在我的版本中看到由于错误而缺少最后一行。

did gyre and gimble in the wabe.
Twas brillig and the slithy toves
and the mome raths outgrabe.
All mimsey were the borogroves,
"Beware the Jabberwock, my son,

Beware the JubJub bird and shun
the jaws that bite, the claws that catch,
the frumious bandersnatch."

这是错误和带有翻转线程序的输出。我不知道为什么当它应该打印最后一行时它会超出令牌索引。

did gyre and gimble in the wabe.
Twas brillig and the slithy toves
and the mome raths outgrabe.
All mimsey were the borogroves,
"Beware the Jabberwock, my son,

Beware the JubJub bird and shun
the jaws that bite, the claws that catch,
NoSuchElementException on line 9:
No tokens remain in input.  Near input line 9

java.util.NoSuchElementException: No tokens remain in input.  Near input line 9
    at Scanner._getNoSuchElementException(Scanner.java:1549)
    at Scanner.nextLine(Scanner.java:1254)
    at flipLines (Line 9)

2 个答案:

答案 0 :(得分:3)

如果行数是奇数,则在检查它只存在一次之后,你不能安全地假设你可以调用nextLine两次。您需要在while循环体内进行额外的检查。

答案 1 :(得分:0)

了解如何解决它,感谢你们让我更仔细地阅读我的代码。我在if语句中添加了一个额外的条件,它现在运行良好!

public static void flipLines(Scanner input) {
    int i = 0;
    while (input.hasNextLine()) {
        String ignore = input.nextLine();
        if (i >= 0 && input.hasNextLine()) {
            String keep = input.nextLine();
            System.out.println(keep);
        } i++;
          System.out.println(ignore);
    }
}