【问题标题】:Entering elements into an array and checking to see if the element already exists [duplicate]将元素输入数组并检查元素是否已经存在[重复]
【发布时间】:2018-12-12 22:08:48
【问题描述】:

我正在解决一个问题,我已经尝试了所有我能想到的 for 循环,但我不知道如何让它工作,因为我只开始使用 c# 和整体编程几周前。

编写一个输入五个数字的应用程序。读取每个数字时,如果数组中不存在该数字,则搜索数组,输出单词“new”并将数字插入数组。如果数组中确实存在该数字,则输出“存在”。输入所有五个数字后,输出数组的内容。

这是我目前所拥有的。感谢您的帮助

using System;

public class Program
{
   // Main method begins execution of C# application
   public static void Main(string[] args)
   {
      int[] array = new int[5];

      for (int i = 0; i < array.Length; i++)
      {
         Console.WriteLine("Enter a number:");
         array[i] = Convert.ToInt32(Console.ReadLine());

         for (int a = 0; a < 5; a++)
         {

            if (array[i] != array[a])
            {
               array[i] = int.Parse(Console.ReadLine());
               Console.WriteLine("new\n");
            }

         }

         array[i] = int.Parse(Console.ReadLine());
         Console.WriteLine("exists\n");
      }

      Console.WriteLine(array);
      Console.ReadKey();
   }
} // end class

【问题讨论】:

  • 家庭作业问题?在我看来,您的代码逻辑似乎不太正确。您正在循环 5 次询问一个数字,然后在其中再次循环 5 次。再看看你如何构建你正在做的事情并在调试器中遵循它
  • 那个问题是关于一个字符串数组,并没有说明如何在输入每个元素时检查它是新的还是存在的
  • @jigmurphy 小的更正将解决这个问题。数组[i] = int.Parse(Console.ReadLine());你为什么在这里读书?并且如果存在打印存在也改变逻辑然后循环结束并且它没有设置为新的。也许你可以添加一个标志
  • 我无法将新元素与数组中的元素进行比较。我已经删除了第二个循环,因为它是不必要的。这样的事情会起作用吗? if (array[i] != array[a])
  • @jigmurphy 我不明白你面临什么问题。在您提供的代码中,您在检查它是否已经存在之前将元素添加到数组中。

标签: c# arrays


【解决方案1】:

在真正开始编写一些代码之前,首先尝试考虑一个解决方案,一些提示

  1. 您期望一些用户输入,我们将使用一个变量来保存用户输入
  2. 您需要验证数组或结构中不存在这些值,这可以使用Contains 方法完成。
  3. 如果存在,我们继续下一个用户输入并打印所需的消息。
  4. 如果该值不存在,我们添加该值并打印新消息

我们会一直这样做,直到结构的Count 等于 5。

作为参考,请使用 While loopHashset.ContainsHashset

试试这个:

var numbers = new HashSet<int>();   
    while(numbers.Count < 5)
    {
         Console.WriteLine("Enter a number:"); //1.
         var number = Convert.ToInt32(Console.ReadLine());

        if (numbers.Contains(number)) // 2.
        {
             Console.WriteLine("exists\n"); //3.
             continue;
        }

        Console.WriteLine("new\n"); //4.
        numbers.Add(number);
    }

    foreach (var n in numbers)
    {
        Console.WriteLine(n);
    }

【讨论】:

    【解决方案2】:

    System.Linq 中使用.Any()。此外,您无需在循环中不断获取用户输入:

    using System;
    using System.Linq;
    
    public class Program
    {
      // Main method begins execution of C# application
      public static void Main(string[] args)
      {
        int[] array = new int[5];
    
        for (int i = 0; i < array.Length; i++)
        {
          Console.WriteLine("Enter a number:");
          // Get user input and convert to integer:
          int input = Convert.ToInt32(Console.ReadLine());
    
          // Check if given input is already in the array: 
          if (! array.Any(number => number == input))
          {
              array[i] = input;
              Console.WriteLine("new\n");
          }
          else 
          {
              Console.WriteLine("exists\n");
          }
        }
    
        // Print the contents of array separated by ','
        Console.WriteLine(string.Join(", ", array));
        Console.ReadKey();
      }
    }
    

    编辑:如果您希望用户完全填充数组,则另一种变体:

    using System;
    using System.Linq;
    
    public class Program
    {
      public static void Main(string[] args)
      {
        // Btw, if this is not an array of nullables,
        // we will not be able to insert a zero later, as
        // we will treat them as duplicates.
        int?[] array = new int?[5];
    
        for (int i = 0; i < array.Length; i++)
        {
          Console.WriteLine("Enter a number:");
    
          int input = 0;
          bool duplicateAttempt = false;
          do {
            // Get and convert the input.
            input = Convert.ToInt32(Console.ReadLine());
            // See if this number is already in.
            duplicateAttempt = array.Contains(input);
            // Report if we attempt to insert a duplicate.
            if (duplicateAttempt) Console.WriteLine("exists");
          } 
          while (duplicateAttempt); // Keep asking while we don't get a unique number.
    
          array[i] = input; // Store the number
          Console.WriteLine("new");
        }
    
        // Print the contents of array separated by ','
        Console.WriteLine(string.Join(", ", array));
        Console.ReadKey();
      }
    }
    

    【讨论】:

    • 但是如果他们输入相同的数字5次,这只会将一项添加到数组中。 OP需要添加5个项目...
    • 非常感谢!这正是我想要的。我将在接下来的时间里弄清楚每个部分是如何工作的,但为此欢呼!
    • @RufusL OP 没有在任何地方说明这一点,但我添加了一个可以做到这一点的编辑。谢谢!
    【解决方案3】:

    您的代码存在一些问题。如果成功,您应该只增加数组索引 - 否则缺失值将为零。在用户输入无效值的情况下验证输入也是一个好主意。您可以使用 linq 检查该值是否已存在于数组中:

    这是一个例子:

        static void Main(string[] args)
        {
            int[] array = new int[5];
            var index = 0; 
            while (index < array.Length)
            {
                Console.WriteLine("Enter a number:");
                var input = Console.ReadLine();
                var value = 0;
                if (!int.TryParse(input, out value))
                {
                    Console.WriteLine("Error - value entered was not a number");
                }
                else
                {
                    var match = array.Where(a => a == value);
                    if (match.Any())
                    {
                        Console.WriteLine("exists\n");
                    }
                    else
                    {
                        array[index] = value;
                        Console.WriteLine("new\n");
                        index++;
                    }
                }
            }
    
            foreach (var item in array)
            {
                Console.WriteLine(item);
            }
    
            Console.ReadKey();
        }
    

    【讨论】:

    • 看起来像一个家庭作业问题..一些提示可能会帮助他入门而不是给出解决方案?
    【解决方案4】:

    这似乎是一个家庭作业问题,所以我认为解释你做错了什么并告诉你应该做什么会更有帮助......

    它不会帮助您学习复制和粘贴其他人的答案。

    using System;
    
    public class Program
    {
       // Main method begins execution of C# application
       public static void Main(string[] args)
       {
          int[] array = new int[5];
    
          for (int i = 0; i < array.Length; i++)
          {
             Console.WriteLine("Enter a number:");
    // you are putting the value into your array here.  so it will always 'exist' below
             array[i] = Convert.ToInt32(Console.ReadLine());  
    
    // you need to do this check before you insert the number into the array
    // put the ReadLine into a variable, not directly into the array.  
    // then check if it's in the array already 
             for (int a = 0; a < 5; a++)
             {
    
                if (array[i] != array[a])
                {
    // here you are trying to read another value from the user.  
    // Console.ReadLine() will always wait for user input
    // use the variable from above.  but only after you have looped through all the items.
    // and verified that it is not present
                   array[i] = int.Parse(Console.ReadLine());
                   Console.WriteLine("new\n");
                }
    
             }
    // this is the third time you have assigned the number to the array
    // and the third time you've asked for user input per loop
             array[i] = int.Parse(Console.ReadLine());
             Console.WriteLine("exists\n");
          }
    
          Console.WriteLine(array);
          Console.ReadKey();
       }
    } // end class
    

    总结一下:

    你需要一个运行 5 次的 for 循环。

    for 循环将执行以下操作:

    • 将用户输入分配给变量
    • 遍历你的数组(第二个循环),看看它是否包含这个变量
    • 如果找到数字,则将布尔值设置为真。 (找到)
    • 如果循环结束后发现=false,则打印false
    • 还将数字添加到数组中(在外循环的索引处即可)

    【讨论】:

      猜你喜欢
      • 2013-11-27
      • 2013-05-06
      • 1970-01-01
      • 1970-01-01
      • 2011-11-14
      • 2016-08-11
      • 2011-06-15
      • 2012-12-31
      相关资源
      最近更新 更多