语法和逻辑错误C#

时间:2018-11-26 05:59:08

标签: c# union hashset

我在调试代码时遇到问题。我在一个图书示例中发现此代码的格式不完整,其中包含语法错误和逻辑错误,并且我会尽力对其进行调试并更正这些错误。但是不幸的是,即使使用调试器,我也无法找出错误。为了更正此代码,我需要做哪些更改?

namespace Exercise_9
{
    class Program
    {
        static void Main(string[] args)
        {
            //make some sets
            //Note, this is where I make the correction within the code. 
            //Originally, this was written as Set A = new Set(); and
            // Set B = new Set(); 

            //Here is the correction by assigning the set variable 
            Set A = new Set();
            Set B = new Set();

            //put some stuff in the sets
            Random r = new Random();
            for (int i = 0; i < 10; i++)
            {
                A.addElement(r.Next(4));
                B.addElement(r.Next(12));
            }

            //display each set and the union
            Console.WriteLine("A: " + A);
            Console.WriteLine("B: " + B);
            Console.WriteLine("A union B: " + A.union(B)); //note, I believe this isnt a proper notation. 

            //display original sets (should be unchanged)
            Console.WriteLine("After union operation");
            Console.WriteLine("A: " + A);
            Console.WriteLine("B: " + B);

        }
    }

}

1 个答案:

答案 0 :(得分:0)

查看代码和注释后,我认为您想利用C#的HashSet数据结构。在这种情况下,您可以尝试执行以下操作:

using System;
using System.Collections.Generic;
namespace Exercise_9
{
   class Program
   {
     static void Main(string[] args)
     {
        HashSet<int> A = new HashSet<int>();
        HashSet<int> B = new HashSet<int>();

        //put some stuff in the sets
        Random r = new Random();
        for (int i = 0; i < 10; i++)
        {
            A.Add(r.Next(4));
            B.Add(r.Next(12));
        }

        //display each set and the union
        Console.WriteLine("Values in A are: ");
        foreach (var value in A) {
            Console.WriteLine(value);
        }

        Console.WriteLine("Values in B are: ");
        foreach (var value in B) {
            Console.WriteLine(value);
        }

        HashSet<int> C = A;
        // storing union in set C using UnionWith
        C.UnionWith(B);

        Console.WriteLine("Values in union set - C are: ");
        foreach (var value in C) {
            Console.WriteLine(value);
        }

        Console.WriteLine("After union operation");

        Console.WriteLine("Values in A are: ");
        foreach (var value in A) {
            Console.WriteLine(value);
        }

        Console.WriteLine("Values in B are: ");
        foreach (var value in B) {
            Console.WriteLine(value);
        }
    }
 }