简体   繁体   中英

Java Text File not able to be read

I'm trying to read in a text file and create an array of objects. I keep getting the following error...

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)

Its not reading the fields and i've tried everything I can think of to fix it. Here is the code. Any advice would be appreciated. Thanks!

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


}
}

For some reason there's a line being read in that doesn't have as many items as you think it does. The scanner has a set of hasNext methods (like hasNextLong() for long values) that tell you whether there's a next item to be scanned and whether the item is of the correct format. Use those methods before getting the next item and you can avoid the error.

You probably want the "While" loop where you're trying to read the inFile within the "try" loop.

If I am not wrong, the file gets closed after this, so you can't really call the scanner on it.

So, you'd go:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM