簡體   English   中英

無法讀取Java文本文件

[英]Java Text File not able to be read

我正在嘗試讀取文本文件並創建對象數組。 我不斷收到以下錯誤...

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


}
}

由於某種原因,正在讀取的行沒有您認為的那么多。 掃描儀具有一組hasNext方法(例如,針對長值的hasNextLong()),它們告訴您是否有下一個要掃描的項目以及該項目的格式是否正確。 在獲得下一項之前,請使用這些方法,這樣可以避免錯誤。

您可能希望在“ While”循環中嘗試在“ try”循環中讀取inFile。

如果我沒看錯,文件將在此之后關閉,因此您無法真正調用掃描器。

所以,你會去:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM