2016-09-09 72 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()應該工作正常

相關問題