尝试从同一个变量中打印多个条目

时间:2012-10-16 21:52:29

标签: c# for-loop while-loop

我很好奇是否有办法可以循环同一个字符串变量的多个条目?基本上我想要将玩家名称的多个条目打印成For循环,但是我有一个脑力,我很难理解如何延伸到目前为止我写的简单代码片段-loop。

    class Program
{
    static void Main(string[] args)
    {
    string choice = "y";
    string player_name = "";

    while (choice == "y")
    {

        Console.WriteLine("Enter the players name: ");
        player_name = Console.ReadLine();


        Console.WriteLine("Would you like to enter another player? y/n");
        choice = Console.ReadLine();

    }
    Console.WriteLine(player_name);

    Console.ReadLine();

    }
}

1 个答案:

答案 0 :(得分:2)

将名称放在列表中,然后遍历列表:

List<string> player_names = new List<string>();

do {

    Console.WriteLine("Enter the players name: ");
    player_name = Console.ReadLine();
    player_names.Add(player_name);

    Console.WriteLine("Would you like to enter another player? y/n");
} while (Console.ReadLine() == "y");

foreach (string name in player_names) {
  Console.WriteLine(name);
}