[英]C# - Assigning user input into a list in a for loop
我正在尝试将用户给定名称分配给名称变量(Player1,Player2等)。
程序要求的播放器数量取决于用户提供的数量(int TotalPlayers)。 因此,如果用户说总数为5,则for循环将要求输入5个名称,而不是更多。
我试图通过首先将所有用户输入添加到列表中,然后在以后将列表中的名称分配到“名称变量”中来实现此目的,但是我似乎无法完成这项工作。
有人可以帮我解决错误,还是有更好的方法来解决此问题?
谢谢!
Console.WriteLine("Write amount of players");
int TotalPlayers = Convert.ToInt32(Console.ReadLine());
List<string> PlayerList = new List<string>();
for (int players = 0; players < TotalPlayers; players++)
{
Console.WriteLine("Enter player {0}'s name:", players + 1);
PlayerList.Add(Console.ReadLine());
}
Console.WriteLine(PlayerList);
看起来是Console.WriteLine(PlayerList);
那会给你带来麻烦。 这将使用基础对象中的内置ToString
方法,这将为您提供
System.Collections.Generic.List`1[System.String]
或类似。
您可以尝试Console.WriteLine(string.Join(", ", PlayerList));
获得一个简单的字符串列表。
在大多数情况下,.Net中默认的字符串生成不是您想要的,并且您将需要遍历列表并自己构建字符串。
上面的代码看起来可以正确执行,但是我认为我们需要更多信息。 您的名称变量是什么样的? 如果您愿意,可以像这样通过循环创建一个列表。
说NameVariable是一些简单的对象。
public class NameVariable
{
public int id {get;set;}
public string Name {get;set;}
}
然后您的代码将类似于:
public static void Main()
{
Console.WriteLine("Write amount of players");
int TotalPlayers = Convert.ToInt32(Console.ReadLine());
List<NameVariable> PlayerList = new List<NameVariable>();
for (int index = 0; index < TotalPlayers; index++)
{
Console.WriteLine("Enter player {0}'s name:", index + 1);
PlayerList.Add(new NameVariable(){
Name = Console.ReadLine(),
Id = index
});
}
foreach(var player in PlayerList)
{
Console.WriteLine(player.Name);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.