在这个存储高分的程序中,我希望用户在一行中输入一个玩家的名字和高分,例如“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
答案 0 :(得分: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) ;
}
根据需要提供错误检查。