2013-04-10 156 views
0

我想讀取文本文件並創建一個對象數組。我不斷收到以下錯誤...Java文本文件無法讀取

Exception in thread "main" java.util.NoSuchElementException 
at java.util.Scanner.throwFor(Unknown Source) 
at java.util.Scanner.next(Unknown Source) 
at Prog6.main(Prog6.java:33) 

它不讀字段,我試過了所有我能想到的解決方法。這是代碼。任何意見,將不勝感激。謝謝!

import java.io.*; 
import java.util.*; 

public class Prog6 
{ 
public static void main(String[] args) 
{ 
    String fname; 
    String lname; 
    String team; 
    String position; 
    int completions; 
    int attempts; 
    int yards; 
    int receptions; 

    Scanner inFile = null; 
    Report rep = new Report(); 

    /* 
    * Open File 
    */ 
    try 
    { 
     inFile = new Scanner(new File("nfl.txt")); 
    } 
    catch (FileNotFoundException e) 
    { 
     System.err.println("Error: file not found"); 
    } 
    /* 
    * Read file 
    */ 

    while (inFile.hasNext()) 
    { 
     fname = inFile.next(); 
     lname = inFile.next(); 
     team = inFile.next(); 
     position = inFile.next(); 
     if (position == "QB") 
     { 
      completions = inFile.nextInt(); 
      attempts = inFile.nextInt(); 
      yards = inFile.nextInt(); 
      Player qb = new Player(); 

      rep.addQuarterback(qb); 
     } 
     else if (position == "WR") 
     { 
      receptions = inFile.nextInt(); 
      yards = inFile.nextInt(); 
      Player wr = new Player(); 

      rep.addReceiver(wr); 
     } 

     // Print report 

     rep.printReport();  
    } 


} 
} 
+2

nfl.txt是怎麼樣的? – JRR 2013-04-10 02:48:40

+0

*「任何建議,將不勝感激..'Prog6.main(Prog6.java:33)'」*看看'Prog6.java'的第33行,並在行尾添加一個註釋,像'//這是它失敗的地方!'。現在您已經確定了該行,請嘗試打印其中引用的任何對象的值。 – 2013-04-10 02:53:29

+0

catch之後的代碼的每一部分都應該放在try中。 – 2013-04-10 02:55:33

回答

0

您可能想要在「嘗試」循環中嘗試讀取inFile的「While」循環。

如果我沒有錯,文件會在這之後關閉,所以您無法真正調用掃描儀。

所以,你會去:

嘗試

{ 
    inFile = new Scanner(new File("nfl.txt")); 
    while(inFile.hasNext()) 
    ..... 
    ..... } 
    catch 
1

出於某種原因,有一個在所讀,你認爲它不具有儘可能多的項目一條線。掃描儀有一組hasNext方法(如long值爲hasNextLong()),告訴您是否有下一個要掃描的項目以及項目的格式是否正確。在獲取下一個項目之前使用這些方法,您可以避免該錯誤。

+1

可能請您在提及'String'比較問題時提及,所以我們沒有第二個問題;) – MadProgrammer 2013-04-10 02:48:43