1

我正在尝试从具有以下格式的 txt 文件中读取:

Matthew:1000
Mark:100
Luke:10
John:0

我有一个存储玩家姓名和分数(int)的分数对象。这是 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;
}

  }

我想以这样一种方式从文件中读取,我可以得到玩家的名字(马修)和他们的分数(1000,存储为整数),并创建一个新的分数对象。这是我到目前为止尝试过的代码:

    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;
}

该函数应该加载已保存分数的字符串表示形式并制作分数的 ArrayList,然后将它们返回给测试函数。当我运行它时,它返回: java.lang.ArrayIndexOutOfBoundsException: 1

任何帮助将不胜感激。

4

1 回答 1

0

试试看

while((fileLine = bufferedReader.readLine()) != null){
    String[] splitResults = fileLine.split(":");
    if (splitResults.length > 1) {
        Score newScore = new Score();
        newScore.playerName = splitResults[0];
        newScore.playerScore = Integer.parseInt(splitResults[1]);
        scores.add(newScore);
    }
}

这将保证只有Split返回至少 2Strings时才会插入。

注意:Integer.parseInt(String string)可以抛出NumberFormatException

于 2013-09-19T00:00:49.330 回答