我确信这只是归结于我不理解StringTokenizer,但我无法在任何地方找到答案。为什么我会收到此错误?
import java.io.*;
import java.util.StringTokenizer;
import java.util.Scanner;
public class NHLDemo {
public static void main(String[] args) throws FileNotFoundException{
File file = new File("nhlstats");
Scanner inputFile = new Scanner(file);
PlayerRecord pr;
NHLStats list = new NHLStats();
while(inputFile.hasNext())
{
String line = inputFile.next();
StringTokenizer token = new StringTokenizer(line, "\t");
while(token.hasMoreTokens()){
System.out.print(token.nextToken());
System.out.print(token.nextToken());
String name = token.nextToken();
String position = token.nextToken();
String team = token.nextToken();
int gp = Integer.parseInt(token.nextToken());
int g = Integer.parseInt(token.nextToken());
int a = Integer.parseInt(token.nextToken());
int pim = Integer.parseInt(token.nextToken());
int sog = Integer.parseInt(token.nextToken());
int gwg = Integer.parseInt(token.nextToken());
pr = new PlayerRecord(name, position, team, gp, g, a, pim, sog, gwg);
list.add(pr);
}
}
list.enumerate();
}
}
我正在从特定文件中读取数据,该文件在每行上具有相同数量的令牌
(来自 St.Louis RW TB 48 17 43 14 112 2
Stamkos C TB 48 29 28 32 157 2
Ovechkin RW WSH 48 32 24 36 220 4
Crosby C PIT 36 15 41 16 124 1等。)
答案 0 :(得分:0)
当你做String line = inputFile.next(); line只是St.Louis,所以当你尝试nextToken时你会得到异常
这有效:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
import java.util.StringTokenizer;
public class MyStringTokenizer {
public static void main(String[] args){
try{
File file = new File("nhlstats");
BufferedReader input=new BufferedReader(new FileReader(file));
//Scanner inputFile = new Scanner(file);
PlayerRecord pr;
NHLStats list = new NHLStats();
String line="";
while((line=input.readLine())!=null)
{
if(!line.equals("")){
StringTokenizer token = new StringTokenizer(line, "\t");
String name = token.nextToken();
String position = token.nextToken();
String team = token.nextToken();
int gp = Integer.parseInt(token.nextToken());
int g = Integer.parseInt(token.nextToken());
int a = Integer.parseInt(token.nextToken());
int pim = Integer.parseInt(token.nextToken());
int sog = Integer.parseInt(token.nextToken());
int gwg = Integer.parseInt(token.nextToken());
pr = new PlayerRecord(name, position, team, gp, g, a, pim, sog, gwg);
list.add(pr);
}
}
input.close();
list.enumerate();
}catch(Exception e){
e.printStackTrace();
}
}
}