以下是我从文本文件中读取的代码:
public RecordManager(){
int pos;
String athlete, record, country, raceTime;
try {
Scanner scFile = new Scanner(new File("resultdata.txt"));
while(scFile.hasNext()){
Scanner sc = new Scanner(scFile.next()).useDelimiter("#");
athlete = sc.next();
country = sc.next();
pos = sc.nextInt();
record = sc.next();
raceTime = sc.next();
sc.close();
if("WRC".equals(record)){
resultArr[size] = new WorldRecord(athlete, country, pos, raceTime);
}
else if("OLR".equals(record)){
resultArr[size] = new OlympicRecord(athlete, country, pos, raceTime);
}
else{
resultArr[size] = new RaceResult(athlete, country, pos, raceTime);
}
size++;
}
} catch (FileNotFoundException ex) {
Logger.getLogger(RecordManager.class.getName()).log(Level.SEVERE, null, ex);
}
以下是文本文件中的内容:
Carey Blem#ITA#6#---#4m49.8
Tammera Hoesly#POR#1#---#4m6.2
Toi Swauger#FRA#1#OLR#51.3
Moises Mellenthin#ZIM#2#---#4m34
Madelene Mcclennon#LUX#1#WRC#1m52.7
Lashon Meisenheimer#RSA#1#---#2m31.2
我一直在尝试和尝试,但我只是继续这样做:
run:
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:907)
at java.util.Scanner.next(Scanner.java:1416)
at it.practical.training.RecordManager.<init>(RecordManager.java:29)
at it.practical.training.SimpleInterface.main(SimpleInterface.java:20)
Java Result: 1
BUILD SUCCESSFUL (total time: 13 seconds)
请告诉我出了什么问题。
答案 0 :(得分:5)
当您使用next()
时,它会读取下一个单词。您的第一行有两个字Carey
和Blem#ITA#6#---#4m49.8
。当您从一行读取单词时,需要使用nextLine()
转到下一行。
我怀疑你真正想要的是
Scanner sc = new Scanner(scFile.nextLine()).useDelimiter("#");
一次读一整行。
答案 1 :(得分:0)
我不完全确定出了什么问题,但我根本不会使用Scanner读取文件。我会使用BufferedReader和循环,而readline方法不返回null。然后我将使用String类的split方法来获取所需的信息。例如
public RecordManager(){
int pos;
String line;
String[] info;
try {
BufferedReader scFile = new BufferedReader(new FileReader(new File("resultdata.txt")));
line = scFile.readLine();
while(line != null){
info = line.split("#");//now athlete is in index 0, country at index 1 etc
if("WRC".equals(info[3])){
resultArr[size] = new WorldRecord(info[0], info[1], info[2], info[4]);
}
else if("OLR".equals(info[3])){
resultArr[size] = new OlympicRecord(info[0], info[1], info[2], info[4]);
}
else{
resultArr[size] = new RaceResult(info[0], info[1], info[2], info[4]);
}
size++;
line = scFile.readLine();
}
} catch (FileNotFoundException ex) {
Logger.getLogger(RecordManager.class.getName()).log(Level.SEVERE, null, ex);
}
}
我知道它并没有直接回答你的代码是什么,但它提供了另一种方法来做你需要的。我希望它无论如何都有帮助。