0

我正在尝试读取一个文本文件并创建一个对象数组。我不断收到以下错误...

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();      
    }


}
}
4

2 回答 2

1

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

于 2013-04-10T02:47:22.947 回答
0

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

如果我没记错的话,文件会在此之后关闭,所以你不能真正调用扫描仪。

所以,你会去:

try {
     inFile = new Scanner(new File("nfl.txt"));        
     while(inFile.hasNext()) {    
         .....      
         ..... 
} catch
于 2013-04-10T02:45:50.003 回答