简体   繁体   English

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

[英]java.util.NoSuchElementException: No line found when line exists in file

I have a Code where I am scanning the lines using Scanner Class and looping till there are no lines left. 我有一个代码,我在其中使用Scanner Class扫描行并循环直到没有行剩余。

My code looks like this: 我的代码如下所示:

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

It gives the error at 它给出了错误

tmp = s.nextLine(); tmp = s.nextLine();

java.util.NoSuchElementException: No line found java.util.NoSuchElementException:找不到行

Which is odd because earlier the same code was working fine. 这很奇怪,因为以前相同的代码可以正常工作。

Why is this line giving an error? 为什么此行显示错误?

Edit: 编辑:

My mistake i did not state the question correctly, i particularly left the try catch block out of the while loop so that i could make an exit when the lines ended...My question is why am i not able to read any of the lines...i have about 3-4 lines to read in the txt file and it is not reading any and giving exception at the first line read itself... 我的错误是我没有正确指出问题,我特别将try catch块留在了while循环之外,以便在行结束时可以退出...我的问题是为什么我无法读取任何行...我有大约3-4行要读取的txt文件,它没有读取任何内容,并且在第一行给出了异常,因此读取了它本身...

I think the better way to code is to have a condition in your while loop using Scanner#hasNextLine() . 我认为更好的编码方式是使用Scanner#hasNextLine()在while循环中添加条件。 Scanner#hasNextLine() would make sure that code inside while would only run if it has a line in the file=. Scanner#hasNextLine()将确保while里面的代码仅在file =中有一行时才运行。

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

should be (if you are trying to check given string is not empty string) 应该是(如果您尝试检查给定的字符串不是空字符串)

if (tmp != null && !tmp.isEmpty())

I think you reach at the end of file where there is no remaining line and your condition is while(true) so it tries to read that time also . 我认为您到达文件末尾,那里没有剩余的行,并且您的条件是while(true),因此它也尝试读取该时间。 So you getting NoSuchElementException(if no line was found ) 所以你得到NoSuchElementException(如果没有找到行)

So better to change your while loop as 因此最好将while循环更改为

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

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM