Here is my code to read from a text file:
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);
}
and here’s what’s in the text file:
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
I have been trying and trying, but I just keep getting this:
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)
Please tell me what’s wrong.
When you use
next()it reads the next word. Your first line has two wordsCareyandBlem#ITA#6#---#4m49.8. When you have read words from a line you need to usenextLine()to go to the next line.I suspect what you really want is
To read a whole line at a time.