1

在这个存储高分的程序中,我希望用户在一行中输入球员的姓名和高分,例如“eric 87”。在用户输入最后一名球员的姓名和分数后,它应该立即列出所有输入的分数。在拆分像“eric 97”这样的字符串时,我不知道该怎么做。非常感谢您的帮助!

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 回答