Reputation: 43
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.
Upvotes: 0
Views: 176
Reputation: 925
I'm not entirely sure what is wrong but I wouldn't use Scanner to read in a file at all. I would use a BufferedReader, and loop while the readline method does not return null. Then I would use the String class' split method to get the information you need. e.g.
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);
}
}
I know it doesn't directly answer what's up with your code but it offers an alternative method of doing what you need. I hope it helps at any rate.
Upvotes: 0
Reputation: 533442
When you use next()
it reads the next word. Your first line has two words Carey
and Blem#ITA#6#---#4m49.8
. When you have read words from a line you need to use nextLine()
to go to the next line.
I suspect what you really want is
Scanner sc = new Scanner(scFile.nextLine()).useDelimiter("#");
To read a whole line at a time.
Upvotes: 5