首页 > 解决方案 > 如何将 if else 语句放入循环中

问题描述

这是我的代码。到目前为止,这是可行的,但我需要它处于一个循环中,所以我不会一直重复这if else句话。

static void Main(string[] args)
        {
            int i, j, k, l, m, n;
            int result;
            string [] array = { "abcw", "baz", "foo", "bar", "xtfn", "abcdef" };
            i = array[0].Length;
            j = array[1].Length;
            k = array[2].Length; 
            l = array[3].Length;
            m = array[4].Length;
            n = array[5].Length;
            result = i * j;
            if (result == 16) 
            {
                Console.WriteLine(result);
            }
            else
            {
                result = i * k;
            }
            if (result == 16)
            {
                Console.WriteLine(result);
            }
            else
            {
                result = i * l;
            }
            if (result == 16)
            {
                Console.WriteLine(result);
            }
            else
            {
                result = i * m;
            }
            if (result == 16)
            {
                Console.WriteLine(array[0]+" * "+array[4]+" = "+result);
            }
            else
            {
                result = i * n;
            }

标签: c#

解决方案


如果您创建一个循环遍历所有条目的外部循环,然后创建一个循环遍历您在外部循环中查看的条目之后的条目的内部循环,您可以执行以下操作

      string[] array = {"abcw", "baz", "foo", "bar", "xtfn", "abcdef"};
      for (var i = 0; i < array.Length; i++)
      {
          for (var j = i + 1; j < array.Length; j++)
          {
              if (array[i].Length * array[j].Length == 16)
              {
                  Console.WriteLine($"{array[i]} {array[j]}");
              }
          }
      }

然后你得到的结果是abcw xtfn


推荐阅读