首页 > 解决方案 > 语法和逻辑错误 C#

问题描述

我无法调试我的代码。我在书本示例中发现此代码形式不完整,包含语法错误和逻辑错误,我尽我所能对其进行调试并纠正这些错误。但不幸的是,即使使用调试器,我也无法找出错误。为了更正此代码,我需要进行哪些更改?

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);

        }
    }

}

标签: c#unionhashset

解决方案


在查看您的代码和评论后,我认为您想利用 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);
        }
    }
 }

推荐阅读