2011-02-03 60 views
1

美好的一天!用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个数字吗?您的帮助将受到高度赞赏。

回答

3

你应该用的是:

String[] parts = sScrores.trim().split("\\s+", 2); 

然后,你将有数目在指数0指数的阵列,并且名称1.

int theNumber = Integer.parseInt(parts[0].trim(); 
String theName = parts[1].trim(); 

你可以重新写入while循环,如下所示:

String sScores=brScores.readLine().trim(); 
while (sScores!=null){ 
     String[] parts = sScrores.trim().split(" +"); 
     int theNumber = Integer.parseInt(parts[0].trim(); 
     if (theNumber < score &&  inserted==false){ 
       vScores.add(score+"\t"+player+"\t"+rank); 
       inserted=true; 
     } 
     vScores.add(sScores); 
     sScores=brScores.readLine(); 
} 

就个人而言,我想补充一个新的HighScore类解析,以帮助 文件。

class HighScore { 

    public final int score; 
    public final String name; 
    private HighScore(int scoreP, int nameP) { 
     score = scoreP; 
     name = nameP; 
    } 

    public String toString() { 
     return score + " " + name; 
    } 

    public static HighScore fromLine(String line) { 
     String[] parts = line.split(" +"); 
     return new HighScore(Integer.parseInt(parts[0].trim()), parts[1].trim()); 
    } 
} 
+0

正在写同样的东西:P – jjczopek 2011-02-03 17:12:20

+0

@jjc,你是对的。 – jjnguy 2011-02-03 17:12:44

+0

使`.split(“+”)` – 2011-02-03 17:12:47

2

每行的格式总是相同的:一个整数,后跟一个制表符,后跟播放器名称。

在解析分数之前,只需查找每行中制表符的索引,以及从0(包含)到此索引(不包括)的子字符串。

玩家名称可以通过从选项卡索引+1(含)以上的行(独占)的长度取得。

1

如果上面提到的表是文件。

对于前两个分数它会很好,但对于5它开始阅读字符。可能是导致问题。