美好的一天!用Java编写文件
我有一个项目(游戏),需要明天上午提出。但是在高分写作时我发现了一个错误。我正在尝试创建一个文本文件,并以分数为基础以降序编写SCORE NAME。
例如:
SCORE NAME RANK
230 God
111 Galaxian
10 Gorilla
5 Monkey
5 Monkey
5 Monkey
还要注意有一个RANK 我的代码如下:
public void addHighScore() throws IOException{
boolean inserted=false;
File fScores=new File("highscores.txt");
fScores.createNewFile();
BufferedReader brScores=new BufferedReader(new FileReader(fScores));
ArrayList vScores=new ArrayList();
String sScores=brScores.readLine();
while (sScores!=null){
if (Integer.parseInt(sScores.substring(0, 2).trim()) < score && inserted==false){
vScores.add(score+"\t"+player+"\t"+rank);
inserted=true;
}
vScores.add(sScores);
sScores=brScores.readLine();
}
if (inserted==false){
vScores.add(score+"\t"+player+"\t"+rank);
inserted=true;
}
brScores.close();
BufferedWriter bwScores=new BufferedWriter(new FileWriter(fScores));
for (int i=0; i<vScores.size(); i++){
bwScores.write((String)vScores.get(i), 0, ((String)vScores.get(i)).length());
bwScores.newLine();
}
bwScores.flush();
bwScores.close();
}
但是,如果我输入三个数字:60曼尼,该文件将是这样的:
60 Manny
230 God
111 Galaxian
10 Gorilla
5 Monkey
5 Monkey
5 Monkey
问题是它只能读取2个数字,因为我用sScores.substring(0, 2).trim())
。 我试着将它改为sScores.substring(0, 3).trim())
。但由于它读取了字符部分而成为错误。任何人都可以帮我修改我的代码,以便我可以读取多达4个数字吗?您的帮助将受到高度赞赏。
正在写同样的东西:P – jjczopek 2011-02-03 17:12:20
@jjc,你是对的。 – jjnguy 2011-02-03 17:12:44
使`.split(“+”)` – 2011-02-03 17:12:47