gpt4 book ai didi

Java 文本文件无法读取

转载 作者:行者123 更新时间:2023-12-01 14:41:28 25 4
gpt4 key购买 nike

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

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()),可以告诉您是否有下一个要扫描的项目以及该项目的格式是否正确。在获取下一项之前使用这些方法可以避免错误。

关于Java 文本文件无法读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15916006/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com