0

このコードを使用して名前とスコアをテキストファイルに保存することで、ハイスコア システムを作成しようとしています。

String text = name.getText().toString() + " " + score.getText().toString();
            appendLog(text);
        }
    });
}

public void appendLog(String text)
{       
   File logFile = new File("sdcard/logger.file");
   if (!logFile.exists())
   {
      try
      {
         logFile.createNewFile();
      } 
      catch (IOException e)
      {
         // TODO Auto-generated catch block
         e.printStackTrace();
      }
   }

   try
   {
      //BufferedWriter for performance, true to set append to file flag
      BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true)); 
      buf.append(text);
      buf.newLine();
      buf.close();
   }
   catch (IOException e)
   {
      // TODO Auto-generated catch block
      e.printStackTrace();
   }

各行に存在するスコアをソートし、対応するスコアで名前を出力する方法はありますか? 誰でもそれを行う方法を教えてもらえますか? ありがとうございました。

4

2 に答える 2

2

行がデータ モデルを表すようにします。つまりEntry、フィールドとして name と score を持つようなクラスを作成します。次に、これらのオブジェクトのリストが表示されます。スコアの降順で並べ替えるカスタム コンパレータを記述します。それだけです=)

于 2013-03-11T14:43:19.620 に答える
0

@juvanisが答えで言ったように、すべてのレコードを表すクラスを作成し、ファイル全体を読み取り、クラスオブジェクトをリストに生成してから、リストをソートし、ソートされた順序でファイルにオブジェクトを書き込みます。

名前とスコアで構成される、レコードを表すために使用されるクラスの例を次に示します。

public class Record {

    private int score;
    private String name;

    public getScore () {
        return score;
    }

    public getName () {
        return name;
    }

    public Record ( String name , int score ) {
        this.name = name;
        this.score = score;
    }

}

名前とスコアのファイルをスコアに基づいて並べ替えるには (レコードを最高のスコアから最低の順に並べ替えたいと思います)、次のメソッドを使用します。

public void sortFile () {

    // Reference to the file
    File file = new File ( "sdcard/logger.file" );
    // Check if the file exists
    if ( ! file.exists () ) {
        // File does not exists
        return;
    }
    // Check if the file can be read
    if ( ! file.canRead () ) {
        // Cannot read file
        return;
    }
    BufferedReader bufferedReader = null;
    // The separator between your name and score
    final String SEPARATOR = " ";
    // A list to host all the records from the file
    List < Record > records = new ArrayList < Record > ();

    try {
        bufferedReader = new BufferedReader ( new FileReader ( file ) );
        String line = null;
        // Read the file line by line
        while ( ( line = bufferedReader.readLine () ) != null ) {
            // Skip if the line is empty
            if ( line.isEmpty () )
                continue;
            // Retrieve the separator index in the line
            int separatorIndex = line.lastIndexOf ( SEPARATOR );
            if ( separatorIndex == -1 ) {
                // Separator not found, file is corrupted
                bufferedReader.close ();
                return;
            }
            // Create a record from this line. It is alright if the name contains spaces, because the last space is taking into account
            records.add ( new Record ( line.substring ( 0 , separatorIndex ) , Integer.parseInt ( line.substring ( separatorIndex + 1 , line.length () ) ) ) );
        }
    } catch ( IOException exception ) {
        // Reading error
    } catch ( NumberFormatException exception ) {
        // Corrupted file (score is not a number)
    } finally {
        try {
            if ( bufferedReader != null )
                bufferedReader.close ();
            } catch ( IOException exception ) {
                // Unable to close reader
            }
    }
    bufferedReader = null;

    // Check if there are at least two records ( no need to sort if there are no records or just one)
    if ( records.size () < 2 )
        return;
    // Sort the records
    Collections.sort ( records , new Comparator < Record > () {
            @Override
            public int compare ( Record record1 , Record record2 ) {
            // Sort the records from the highest score to the lowest
                    return record1.getScore () - record2.getScore ();
            }
    } );

    // Replace old file content with the new sorted one
    BufferedWriter bufferedWriter = null;
    try {
        bufferedWriter = new BufferedWriter ( new FileWriter ( file , false ) ); // Do not append, replace content instead
        for ( Record record : records ) {
            bufferedWriter.append ( record.getName () + SEPARATOR + record.getScore () );
            bufferedWriter.newLine ();
        }
        bufferedWriter.flush ();
        bufferedWriter.close ();
    } catch ( IOException exception ) {
        // Writing error
    } finally {
        try {
            if ( bufferedWriter != null )
                bufferedWriter.close ();
        } catch ( IOException exception ) {
            // Unable to close writer
        }
    }
    bufferedWriter = null;

    // You can output the records, here they are displayed in the log
    for ( int i = 0 ; i < records.size () ; i ++ )
        Log.d ( "Record number : " + i , "Name : \"" + records.get ( i ).getName () + "\" , Score : " + records.get ( i ).getScore () );

}

ご不明な点がございましたら、お気軽にお問い合わせください。試してみて、意図したとおりに機能するかどうかを最新の状態に保ちます。

于 2013-03-11T15:33:07.240 に答える