【问题标题】:Trying to print multiple entries from the same variable尝试从同一个变量打印多个条目
【发布时间】:2012-10-16 21:52:28
【问题描述】:

我很好奇是否有一种方法可以循环同一字符串变量的多个条目?基本上,我想将玩家姓名的多个条目打印到 For 循环中,但是我脑子有问题,我很难理解如何扩展我迄今为止编写的简单代码段-循环。

    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();

    }
}

【问题讨论】:

  • 将 WriteLine(player_name) 放入 while 循环不起作用?

标签: c# for-loop while-loop


【解决方案1】:

将名字放在一个列表中,然后遍历列表:

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);
}

【讨论】:

  • 列表!我还没有使用过那个,但这正是我需要它做的。感谢您的快速回复。
猜你喜欢
  • 2019-10-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-14
  • 1970-01-01
  • 1970-01-01
  • 2018-08-09
相关资源
最近更新 更多