1

ハイスコ​​アを保存するこのプログラムでは、ユーザーにプレーヤーの名前とハイスコアを1行で入力してもらいます(例:「eric87」)。ユーザーが最後のプレーヤーの名前とスコアを入力した後、入力されたスコアを一度に一覧表示する必要があります。「eric97」のように文字列を分割するときにこれを行う方法がわかりません。助けてくれてありがとう!

const int MAX = 20;
static void Main()
{
    string[ ] player = new string[MAX];
    int index = 0;

    Console.WriteLine("High Scores ");
    Console.WriteLine("Enter each player's name followed by his or her high score.");
    Console.WriteLine("Press enter without input when finished.");

    do {
        Console.Write("Player name and score: ", index + 1);
        string playerScore = Console.ReadLine();
        if (playerScore == "")
            break;
        string[] splitStrings = playerScore.Split();
        string n = splitStrings[0];
        string m = splitStrings[1];


    } while (index < MAX);

    Console.WriteLine("The scores of the player are: ");
    Console.WriteLine("player \t Score \t");

  //  Console.WriteLine(name + " \t" + score);
    // scores would appear here like:
    // george 67
    // wendy 93
    // jared 14
4

1 に答える 1

3

コードを見ると、プレーヤー配列を使用していません。ただし、よりオブジェクト指向のアプローチをお勧めします。

public class PlayerScoreModel
{
    public int Score{get;set;}

    public string Name {get;set;}
}

プレーヤーとスコアをに保存しList<PlayerScoreModel>ます。

そして、最後のユーザーとスコアが入力されたら、リストを繰り返し処理します。

 do {
        Console.Write("Player name and score: ", index + 1);
        string playerScore = Console.ReadLine();
        if (playerScore == "")
            break;
        string[] splitStrings = playerScore.Split();
        PlayerScoreModel playerScoreModel = new PlayerScoreModel() ;

        playerScoreModel.Name = splitStrings[0];
        playerScoreModel.Score = int.Parse(splitStrings[1]);
        playerScoreModels.Add(playerScoreModel) ;

    } while (somecondition);

   foreach(var playerScoreModel in playerScoreModels)
   {
      Console.WriteLine(playerScoreModel.Name +" " playerScoreModel.Score) ;
    }

必要に応じてエラーチェックを行います。

于 2012-12-14T03:00:42.067 に答える