我正在尝试读取文本文件并创建一个对象数组。我一直收到以下错误......
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();
}
}
}
答案 0 :(得分:1)
由于某种原因,读入的行没有您认为的那么多项目。扫描仪有一组hasNext方法(如long值的hasNextLong()),它们告诉您是否有下一个要扫描的项目以及该项目的格式是否正确。在获取下一个项目之前使用这些方法,您可以避免错误。
答案 1 :(得分:0)
你可能想要“while”循环,你试图在“try”循环中读取inFile。
如果我没错,那么文件会在此之后关闭,因此您无法真正调用扫描程序。
所以,你会去:
try {
inFile = new Scanner(new File("nfl.txt"));
while(inFile.hasNext()) {
.....
.....
} catch