2013-03-28 37 views
0

存在行我有我在哪里使用扫描仪类和循环线一码,直到没有剩下线。java.util.NoSuchElementException:没有找到线时文件

我的代码看起来是这样的:

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循环,这样我可以做一个出口,当行结束...我的问题是,为什么我不是能够读取任何行...我有大约3-4线路中的TXT文件阅读和它没有任何阅读,并在第一线给予例外阅读本身......

+0

这是一个依赖问题... –

+0

您是否尝试过阅读的JavaDoc? http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#nextLine() – Keppil

+0

@JacoVanNiekerk:在我应该怎么办?... –

回答

1
if (tmp != null && tmp.equals("")) 

应该是(如果你想检查指定的字符串不是空字符串)

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

我想你达到在文件末尾不存在剩余行和你的条件是(true),所以它也试图读取那个时间。所以,你得到NoSuchElementException异常(如果没有行被发现)

因此,更好地改变你的while循环

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

} 
+0

在这个'if'之前抛出异常# – Ilya

+0

@Ilya到达EOF时会发生什么。它仍然试图读取巢线,条件是(true) –

2

我想更好的代码方式是在你的while循环中使用Scanner#hasNextLine()。扫描程序#hasNextLine()将确保内部代码只在文件中有一行时运行。

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