c# - 语法和逻辑错误 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# 的 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);
}
}
}
推荐阅读
- python - 如何在 Python 中抓取网页
- c# - Linq 方法左连接两个列表以获得扁平列表
- c++ - 使用 c++ 偶尔检测到 *** 堆栈粉碎***
- javascript - 使用 React Big Calendar 如何更改我指向的单元格的颜色
- google-sheets-formula - 即使条件检查为空,谷歌表格查询也会返回带有空单元格的行
- java - 有什么方法可以匹配 Iterable 中的模式
在 Java 中? - ios - iOS Core Graphics如何将CGImage的中间行作为vImage_Buffer?
- python - 在 x,y=0 处评估具有明确定义值的函数
- magento2 - Magento 2:将自定义过滤器添加到选项类选择 ui 组件
- php - 为什么 php strpos() 有时不适用于 Unicode 字符?