簡體   English   中英

比較書面文件中的字符串

[英]Comparing strings from a written file

我被學校上的這個程序困住了。 這是我的代碼:

public static void experiencePointFileWriter() throws IOException{

    File writeFileResults = new File("User Highscore.txt");

    BufferedWriter bw;

    bw = new BufferedWriter(new FileWriter(writeFileResults, true));

    bw.append(userName + ": " + experiencePoints);
    bw.newLine();
    bw.flush();
    bw.close();

    FileReader fileReader = new FileReader(writeFileResults);

    char[] a = new char[50];
    fileReader.read(a); // reads the content to the array
    for (char c : a)
        System.out.print(c); // prints the characters one by one
    fileReader.close();

}

我面臨的難題是如何將新成績與writeFileResults中的成績按int experiencePoints的數值排序? 如果您想知道變量userName是由textfield.getText方法分配的,那么當您按下36個按鈕之一啟動一個math.Random語句,並帶有24種可能的結果之一時,就會發生一個事件。 它們都將不同的整數添加到experiencePoints。

好吧,我不想做你的家庭作業,而且這似乎是介紹性的,所以我想給你一些提示。

首先,缺少一些東西:

  1. 我們沒有您提供的一些變量,因此沒有與oldScores相關的類型
  2. 在此方法調用之外沒有對userNameexperiencePoints引用

如果您可以添加此信息,它將使此過程更加容易。 我可以推斷出一些東西,但是后來我可能錯了,或者更糟的是,您沒有學到任何東西,因為我為您做了作業。 ;)

編輯:

因此,基於額外的信息,您的數據文件中包含用戶名和體驗值的“數組”。 因此,最好的方法(閱讀:最好的設計,而不是最短的方法)是將它們加載到自定義對象中,然后編寫比較器函數(閱讀:實現抽象類Comparator )。

因此,在偽Java中,您將具有:

  1. 聲明您的數據類型:

     private static class UserScore { private final String name; private final double experience; // ... fill in the rest, it's just a data struct } 
  2. 在您的閱讀器中,當您讀取值時,請分割每一行以獲取值,然后創建一個新的List<UserScore>對象,該對象包含從文件中讀取的所有值(我將讓您了解這一部分)
  3. 擁有列表后,可以使用Collections#sort將列表排序為正確的順序,下面是一個示例:

     // assuming we have our list, userList Collections.sort(userList, new Comparator<UserScore>() { public int compare(UserScore left, UserScore right) { return (int)(left.getExperience() - right.getExperience()); // check the docs to see why this makes sense for the compare function } } // userList is now sorted based on the experience points 
  4. 根據需要重新編寫文件。 您現在有了一個排序列表。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM