在文件末尾突破循环

时间:2015-05-13 02:33:22

标签: java java.util.scanner

当所有行都被读完时,我试图突破循环。我已经尝试使用String temp = scan.nextLineif temp.equals("") break,但这并没有在正确的时间突破循环。

我希望它一直读到文件末尾,然后退出循环,除了while scan.hasNextLine()在读取文件中的最后一个值时仍然评估为true。

代码:

int line = 0;
while (scan.hasNextLine()) {
    System.out.println("reading first line");
    //means we're reading the board coordinates
    if (line == 0) {
        System.out.println("first line");
        boardX = scan.nextInt();
        System.out.println("boardX: " + boardX);
        boardY = scan.nextInt();
        System.out.println("boardY: " + boardY);
    }
    //we're reading the non smokers positions and storing them in an array
    int nonSmokersPosX;
    int nonSmokersPosY;
    nonSmokersPosX = scan.nextInt();
    nonSmokersPosY = scan.nextInt();
    System.out.println("non smokers position: " + nonSmokersPosX + " " + nonSmokersPosY);
    pairedCoordinates.add(new Pair(nonSmokersPosX, nonSmokersPosY));
    line++;
}

输入:

9 8
0 1
5 6
3 2

输出:

reading first line
first line
boardX: 9
boardY: 8
non smokers position: 0 1
reading first line
non smokers position: 5 6
reading first line
non smokers position: 3 2
reading first line
Exception in thread "main" java.util.NoSuchElementException

5 个答案:

答案 0 :(得分:2)

您可以使用使用hasNext()函数的while循环。像这样:

while(scan.hasNextLine()) {...}

此外,您可以检查您正在阅读的文本文件是否在末尾没有多余的行。您也可以尝试.hasNext()

答案 1 :(得分:1)

有两种解决方案。您希望在while条件下检查什么;是否至少还有一个或多一行?

  1. 再多一个号码
  2. 然后检查是否至少还有一个号码:while (scan.hasNextInt()) {

    1. 又一行
    2. 然后确保首先完全读取当前行。扫描仪必须先超过当前行的末尾才能确定是否有更多行。 因此,作为while循环中的最后一条语句,请添加:scan.nextLine();

      这两种解决方案都可以使您的代码正常运行。

答案 2 :(得分:0)

您的while循环已经具有以下条件:while (scan.hasNextLine())。这意味着继续前进,直到我们有下一行,如果我们不退出循环。

答案 3 :(得分:0)

此外,您可能希望清理代码。您的打印步骤不正确,并且不遵循程序的逻辑。

int line = 0;
while (scan.hasNextLine()){
        System.out.println("reading first line");
        //means we're reading the board coordinates
        if (line == 0){
            System.out.println("first line");
            boardX = scan.nextInt();
            System.out.println("boardX: "+boardX);
            boardY = scan.nextInt();
            System.out.println("boardY: "+boardY);
        } else {
        //we're reading the non smokers positions and storing them in an array
        int nonSmokersPosX;
        int nonSmokersPosY;
        nonSmokersPosX = scan.nextInt(); // <-- This is where your code was previously failing.
        nonSmokersPosY = scan.nextInt();
        System.out.println("non smokers position: "+nonSmokersPosX+" "+nonSmokersPosY);
        pairedCoordinates.add(new Pair(nonSmokersPosX, nonSmokersPosY));
   }
        line++;

}

答案 4 :(得分:0)

您告诉我们您的输入是:

9 8
0 1
5 6
3 2

我问,你的EOF在哪里?当我过去对这些作业进行评分时,如果您的最后一行数据以EOF或其他新行结尾,那么会产生重大影响。

怎么说?打开输入文件并运行闪烁的光标(有些人称之为插入符号)到最后。它是停在2的右边还是3的下方?

一旦你知道这个并不难编程,但是当你不这样做时调试就会令人抓狂。希望它有所帮助。

相关问题