Wednesday, 18 September 2013

I want to read a file line by line and split the strings to be used as attributes for a new object

I want to read a file line by line and split the strings to be used as
attributes for a new object

I'm trying to read from a txt file that has the following format:
Matthew:1000
Mark:100
Luke:10
John:0
Actually, there is no extra space between the lines, I just couldn't get
it to look like that.
I have a Score object that stores the player's name and score (int). This
is the class for Score:
public class Score {
String playerName;
int playerScore;
public String toString(){
StringBuilder builder = new StringBuilder();
builder.append(playerName + ":" + playerScore);
return builder.toString();
}
public void setName(String name){
this.playerName = name;
}
public void setScore(int score){
this.playerScore = score;
}
}
I would like to read from the file in such a way that I could get the
player's name (Matthew) and their score (1000, stored as an integer), and
make a new Score object. This is the code I've tried so far:
public ArrayList getLoadFile(String filename) {
ArrayList<Score> scores = new ArrayList<Score>();
BufferedReader bufferedReader = null;
try{
bufferedReader = new BufferedReader(new FileReader(filename));
String fileLine;
while((fileLine = bufferedReader.readLine()) != null){
Score newScore = new Score();
newScore.playerName = fileLine.split(":", 0)[0];
newScore.playerScore = Integer.parseInt(fileLine.split(":",
0)[1]);
scores.add(newScore);
}
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
return scores;
}
This function is supposed to load string representations of saved scores
and make an ArrayList of scores, then return them to a test function. When
I run it, it returns: java.lang.ArrayIndexOutOfBoundsException: 1
Any help would be greatly appreciated.

No comments:

Post a Comment