【问题标题】:How to repeat a console.writeline x times in c#?如何在 c# 中重复 console.writeline x 次?
【发布时间】:2018-05-09 09:57:18
【问题描述】:

我正在尝试将 console.writeline 重复 x 次(在 C# 中)。

x(long 类型)是来自 console.writeline 的用户输入。因此,如果 x 为 2,我希望 2 个 console.writelines 跟随它。 我尝试使用 Enumerable.Repeat 修复它,但没有奏效。还有一个while循环,我从x中减去1直到它为0并没有成功。 建议?

【问题讨论】:

  • 有什么理由不想只使用for 循环? for (int i = 0; i < x; i++) { Console.WriteLine(...); }?
  • for 循环,也许??
  • 你能提供一些代码吗?
  • 有任何证据不起作用?可能你的条件不对
  • this answer 的可能副本,有一些巧妙的解决方案。

标签: c# repeat console.writeline


【解决方案1】:

类似的东西?

static void Main(string[] args)
{
    var input = Console.ReadLine();

    long loopCounter = 0;
    long.TryParse(input, out loopCounter);

    for (int i = 0; i < loopCounter; i++)
    {
        Console.WriteLine("My Message");
    }

    Console.ReadKey();
}

【讨论】:

  • 我没有使用 for 循环,因为它与 while 循环的效果相同。因为对于每个写行,我还需要一个读行来读取它,而且空间真的很大。
  • @Amber 哪个效果?真的不清楚你的问题到底是什么......
  • @Amber 那么这个答案正确吗?如果是,请标记它。
【解决方案2】:

没有循环的方法,如其他 cmets 所述。如果这符合您的需求,请标记为答案。请注意,它必须是 int。

class Program
{
      static void Main(string[] args)
      {
           string input = Console.ReadLine();
           int d;
           if (int.TryParse(input, out d))
           Console.WriteLine(string.Concat(Enumerable.Repeat("Whatever",d)));
           Console.ReadLine();
      }
}

【讨论】:

  • 为什么有人放-1?
  • @Amber 试试我的解决方案,它只需要在没有任何循环的情况下长时间 int。
  • 谢谢!这为我节省了一些 for 循环!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-12-03
  • 1970-01-01
  • 2012-11-07
  • 2015-08-22
  • 1970-01-01
  • 2019-12-23
  • 1970-01-01
相关资源
最近更新 更多