将元素追加到List <int>,直到输入指定的值?</int>

时间:2013-12-21 15:13:57

标签: c# list

List<int> numbers = new List<int>();

    do
    {
        numbers.Add(int.Parse(Console.ReadLine()));
    } 
    while ();

我正在尝试解决以下问题:编写一个程序,查找数组中相等元素的最大序列。         示例:{2,1,1,2,3,3,2,2,2,1} - &gt; {2,2,2}。

所以我想从输入列表的元素开始,因为我不想事先指定序列的长度,以使其适用于任何给定的长度。

我想在输入特定值(例如-1,或逗号或其他内容)时停止向列表中添加更多元素。我已经提出了上面的代码,我只需要找出使用什么条件来实现我的想法。也许我需要一种完全不同的方法......你告诉我。

3 个答案:

答案 0 :(得分:2)

您可以执行以下操作:读取控制台,直到读取特殊字符串;尝试另外解析:

static void Main(string[] args) {
  List<int> numbers = new List<int>();

  while (true) {
    String line = Console.ReadLine();

    // Put here your condition(s) to break the input: -1, comma... 
    if (String.Equals(line, "-1", StringComparison.Ordinal))
      break;

    int v;

    if (int.TryParse(line, out v))
      numbers.Add(v);
    else 
      Console.WriteLine("Sorry, this incorrect number is ignored.");
  }

  // You've done with the input: numbers contains all the integers you have to analyze
  ... 
}

P.S。实际上,要解决问题,你不需要 List<int>:你可以使用到目前为止最大序列的长度(以及在其中重复的数字);和当前序列长度和在其中重复的数字

答案 1 :(得分:1)

您可以使用int.TryParse。那么除了数字之外的任何东西都会破坏循环。

static void Main(string[] args)
{
    List<int> numbers = new List<int>();
    int inputNumber;

    while (int.TryParse(Console.ReadLine(), out inputNumber))
    {
        numbers.Add(inputNumber);
    }
}

如果您希望在值为-1时中断循环,则只需添加if

while (...)
{
    if (inputNumber == -1) break;
    ...
}

对于“数组中相等元素的最大序列”,您可以检查现有解决方案

答案 2 :(得分:0)

你可以试试这个:

int newInt = -1;
while(int.TryParse(Console.ReadLine(), out newInt) && newInt > -1)
{
  numbers.Add(newInt)
} 

你不需要做什么,因为如果满足条件,你只需要在while循环中运行代码。
另外int.TryParse在这个句子中非常方便,因为如果字符串输入可以与int相关,它将返回true。它还通过out newInt将转换后的值转换为变量newInt