2013-12-08 57 views
0

當我嘗試運行此並調用此特定方法時,我得到NoSuchElementException。它工作得很好,然後我將其更改爲ArrayList,而不是直接從文件Scanner直接讀取/打印。NoSuchElementException當打印從文件填充我的ArrayList

以下是它說當我選擇選項2 ArrayList]:

異常線程 「main」 java.util.NoSuchElementException
在java.util.Scanner.throwFor(來源不明)
在java.util.Scanner.next(未知來源)
在version4.version4.readDisplay(version4.java:79)
在version4.version4.main(version4.java:27)

我的代碼:

public class version4 
{ 
    public static void main(String[] args) throws FileNotFoundException 
    { 
     Scanner in = new Scanner(System.in); 
     boolean exit = false; 

     while (!exit) 
     { 
      System.out.println("1 Find an item.\n2 Display all items.\n3 Update item.\n4   Save item to disk.\n5 Quit."); 
      int choice = in.nextInt(); 
      switch (choice){ 

       case 1: System.out.println("You chose to find an item from file."); findItem(); break; 
       case 2: System.out.println("You chose to display all items."); readDisplay(); break; 
       case 3: System.out.println("You chose to update an item."); itemUpdate(); break; 
       case 4: System.out.println("You chose to save an item to disk."); itemAdd(); break; 
       case 5: exit = true; break; 
       default: System.out.println("That is not a valid option."); break; 
      } 
     } 
     System.out.println("Goodbye."); 
    } 

    public static void readDisplay() throws FileNotFoundException 
    {   
     // Open input file: 
     System.out.println("Reading 'read_record.txt'"); 
     FileReader reader = new FileReader("read_record.txt"); 
     Scanner fin = new Scanner(reader); 
     String str = null; 
     ArrayList<String> dvdfile = new ArrayList<String>(); 
     while((str = fin.next()) != null){ 
      dvdfile.add(str); 
     } 

     Iterator iter = dvdfile.iterator(); 
     while (iter.hasNext()) 
     { 
      String sku = (String) iter.next(); 
      String title = (String) iter.next(); 
      String length = (String) iter.next(); 
      System.out.printf("%-10s %-15s %10s %n",sku,title,length); 
     } 

     // Close file: 
     fin.close(); 
    } 
} 

任何人都知道什麼導致NoSuchElementException和/或如何解決?

+0

加入iter.next()多次的iter.hasNext(內部)將始終有機會拋出NoSuchElementException異常。 –

+0

這部分沒有拋出異常,我仍然保持原樣,並且在Elliot修復後仍能正常工作。 – Corey

回答

0

可能有幾件事情怎麼回事......我想嘗試這個

if (fin != null && fin.hasNext()) { // do we have a scanner, is there anything to read? 
    while (fin.hasNext()) { // while there's something to read... 
    str = fin.next(); // read it. 
    if (str == null) { // end if it's null? 
     break; 
    } 
    dvdfile.add(str); // otherwise add it. 
    } 
} 
+0

不完全明白爲什麼,但這工作!謝謝! – Corey