Java文本文件无法读取

问题描述:

我想读取文本文件并创建一个对象数组。我不断收到以下错误...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

您可能想要在“尝试”循环中尝试读取inFile的“While”循环。

如果我没有错,文件会在这之后关闭,所以您无法真正调用扫描仪。

所以,你会去:

尝试

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

出于某种原因,有一个在所读,你认为它不具有尽可能多的项目一条线。扫描仪有一组hasNext方法(如long值为hasNextLong()),告诉您是否有下一个要扫描的项目以及项目的格式是否正确。在获取下一个项目之前使用这些方法,您可以避免该错误。

+1

可能请您在提及'String'比较问题时提及,所以我们没有第二个问题;) – MadProgrammer 2013-04-10 02:48:43