2016-09-09 129 views
-1

我有一个由这样的异常线程“main” java.util.NoSuchElementException

/1/a/a/a/Female/Single/a/a/January/1/1920/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a/a 

和这里的文件是我的StringTokenizer代码:

public void retrieveRecords(){ 
     String holdStr=""; 
     try { 
      fileRead=new FileReader(fileNew); 
      read=new Scanner(fileRead); 

      while(read.hasNext()){ 
       holdStr+=read.nextLine()+"\n"; 
      } 
      read.close(); 

      StringTokenizer strToken=new StringTokenizer(holdStr, "/"); 

      while(strToken.hasMoreElements()){ 
       rows=new Vector(); 
       for(int i=0; i<column.length; i++){ 
        rows.add(strToken.nextElement()); 
       } 
       ViewTablePanel.tblModel.addRow(rows); 
      } 

     } catch (FileNotFoundException e) { 
      e.printStackTrace(); 
     } 

我居然没有任何想法是什么问题,以及我研究为什么nosuchelementexception会发生的每一个原因,但我没有做所有这些原因,为什么它不会工作。任何建议将是开放的太感谢你了:)

+0

在哪一行发生异常?另外,请阅读关于发布[最小,完整和可验证示例](http://stackoverflow.com/help/mcve)。 – Jezor

+5

你的while循环调用'hasMoreElements()',但在它的内部有一个for循环,多次调用nextElement()。根据javadoc,如果没有更多元素,'nextElement()'可能会抛出NoSuchElementException异常。 – FatalError

+0

请阅读[如何创建最小,完整和可验证示例](http://stackoverflow.com/help/mcve)。例如,您可以直接从代码片段中的字符串创建一个标记器,而不是从文件读取。这使得它更容易重现。什么是“ViewTablePanel”,重现问题很重要吗? –

回答

1

异常java.util.NoSuchElementException抛出此异常以表明标记器中没有更多元素。

while(strToken.hasMoreElements()){ 
     rows=new Vector(); 
     for(int i=0; i<column.length; i++){ 
      rows.add(strToken.nextElement()); //Exception will throw on this line 
     } 
     ViewTablePanel.tblModel.addRow(rows); 
    } 

在你while循环必须检查使用hasMoreElements()多个元素的条件。但是在while循环中,你有多次调用nextElement()的循环。如果标记器中没有元素,则nextElement()将丢弃java.util.NoSuchElementException

解决方案:在for循环中添加一些条件来检查标记器中的元素。

1
while(read.hasNext()){ 

      holdStr+=read.nextLine()+"\n"; 
    } 

从以上,扫描仪读取没有任何标记生成器,因此,read.hasNext()抛出NoSuchElementException异常read.hasNextLine()应该工作正常

相关问题