C# 将元素附加到列表<;int>;直到输入指定值为止? 列表编号=新列表(); 做 { Add(int.Parse(Console.ReadLine()); } while();

C# 将元素附加到列表<;int>;直到输入指定值为止? 列表编号=新列表(); 做 { Add(int.Parse(Console.ReadLine()); } while();,c#,list,C#,List,我试图解决以下问题:编写一个程序,查找数组中相等元素的最大序列。 例如:{2,1,1,2,3,3,2,2,2,1}-->{2,2,2} 因此,我想从输入列表的元素开始,因为我不想预先指定序列的长度,以使其在任何给定的长度下工作 我希望在输入特定值(如-1、逗号等)时,停止向列表中添加更多元素。我已经想出了上面的代码,我只需要找出要实现我的想法需要使用什么条件。也许我需要一个完全不同的方法。。。你告诉我 您可以使用。那么除了数字以外的任何东西都会打破循环 List<int> numbe

我试图解决以下问题:编写一个程序,查找数组中相等元素的最大序列。 例如:{2,1,1,2,3,3,2,2,2,1}-->{2,2,2}

因此,我想从输入列表的元素开始,因为我不想预先指定序列的长度,以使其在任何给定的长度下工作

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

您可以使用。那么除了数字以外的任何东西都会打破循环

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

    do
    {
        numbers.Add(int.Parse(Console.ReadLine()));
    } 
    while ();
至于“数组中相等元素的最大序列”,您可以检查现有的解决方案

    • 您可以尝试以下方法:

      while (...)
      {
          if (inputNumber == -1) break;
          ...
      }
      
      您不需要执行while,因为如果满足条件,您只需要while循环中的代码即可运行。

      在这个senario中也非常方便,因为如果字符串输入可以转换为int,它将返回
      true
      。它还将通过
      out newInt
      转换的int传递给您,将值放入变量
      newInt

      ,您可以执行如下操作:读取控制台,直到读取特殊字符串;请尝试以其他方式进行分析:

      int newInt = -1;
      while(int.TryParse(Console.ReadLine(), out newInt) && newInt > -1)
      {
        numbers.Add(newInt)
      } 
      
      static void Main(字符串[]args){
      列表编号=新列表();
      while(true){
      String line=Console.ReadLine();
      //在这里输入您的条件以中断输入:-1,逗号。。。
      if(String.Equals(行“-1”,StringComparison.Ordinal))
      打破
      INTV;
      if(内锥巴色(第五行))
      增加(五);
      其他的
      Console.WriteLine(“对不起,此错误号码被忽略。”);
      }
      //您已经完成了输入:数字包含您必须分析的所有整数
      ... 
      }
      

      另外,实际上,要解决这个问题,您不需要
      列表
      :您可以使用迄今为止最大序列的长度(以及其中重复的数字);以及在其中重复的当前序列长度和编号

      将输入保存在一个变量中,并在条件中进行检查..+1以确保清晰,但您忘记了使用-1终止条件
      int newInt = -1;
      while(int.TryParse(Console.ReadLine(), out newInt) && newInt > -1)
      {
        numbers.Add(newInt)
      } 
      
      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
        ... 
      }