java.util.NoSuchElementException:文件中存在行时未找到行

java.util.NoSuchElementException:文件中存在行时未找到行,java,java.util.scanner,Java,Java.util.scanner,我有一个代码,我使用Scanner类扫描行,并循环直到没有行了 我的代码如下所示: File file = new File(filePath); if (file.exists()) { Scanner s = new Scanner(file); String tmp = null; int result = 0; try { while (true) { tmp = s.nextLine();

我有一个代码,我使用Scanner类扫描行,并循环直到没有行了

我的代码如下所示:

File file = new File(filePath);

if (file.exists()) {
    Scanner s = new Scanner(file);
    String tmp = null;
    int result = 0;
    try {
        while (true) {
            tmp = s.nextLine();
            if (tmp != null && tmp.equals("")) {
                result += Integer.parseInt(tmp);
            }
            System.out.println(runSequence(Integer.parseInt(tokens[0])));
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    System.out.println(result);
}
它给出了以下错误:

tmp=s.nextLine()

java.util.NoSuchElementException:未找到任何行

这很奇怪,因为之前相同的代码运行良好

为什么这一行给出了一个错误

编辑:


我的错误我没有正确陈述问题,我特别将try-catch块放在while循环之外,以便在行结束时退出…我的问题是为什么我不能读取任何行…我在txt文件中有大约3-4行要读取,它没有读取任何行,并且在第一行读取自身时出现异常…

我认为更好的编码方法是使用while循环中的条件。Scanner#hasNextLine()将确保while中的代码只有在文件=”中有一行时才会运行

              while (s.hasNextLine()) {
                tmp = s.nextLine();
                if (tmp != null && tmp.equals("")) {
                    result += Integer.parseInt(tmp);
                }

我认为更好的编码方法是在while循环中使用一个条件。Scanner#hasNextLine()将确保while中的代码只有在文件=”中有一行时才会运行

              while (s.hasNextLine()) {
                tmp = s.nextLine();
                if (tmp != null && tmp.equals("")) {
                    result += Integer.parseInt(tmp);
                }
应该是(如果您试图检查给定字符串是否为空字符串)

我想你到达了文件的末尾,那里没有剩余的行,你的条件是while(true),所以它也尝试读取那个时间。所以您得到的是NoTouchElementException(如果没有找到行)

因此,最好将while循环更改为

while (s.hasNextLine()){  
   tmp = s.nextLine();
   // then do something

}
应该是(如果您试图检查给定字符串是否为空字符串)

我想你到达了文件的末尾,那里没有剩余的行,你的条件是while(true),所以它也尝试读取那个时间。所以您得到的是NoTouchElementException(如果没有找到行)

因此,最好将while循环更改为

while (s.hasNextLine()){  
   tmp = s.nextLine();
   // then do something

}

这是一个依赖性问题……您是否尝试过阅读JavaDoc@JacoVanNiekerk:就像我应该做什么一样…?这是一个依赖性问题…你试过阅读JavaDoc吗@JacoVanNiekerk:就像我应该做什么一样…?异常会在
if
之前抛出。Ilya当你到达EOF时会发生什么。当(true)异常在此
之前抛出时,它仍然尝试按条件读取嵌套行,如果
@Ilya当您到达EOF时会发生什么。当条件为while(true)时,它仍尝试读取嵌套行
while (s.hasNextLine()){  
   tmp = s.nextLine();
   // then do something

}