【问题标题】:C# How to verify if the position is empty in a jagged array?C#如何验证锯齿状数组中的位置是否为空?
【发布时间】:2017-07-12 16:53:46
【问题描述】:

所以,我需要制作这个结构

职位:

0 - {2, 5, 7, 8}

1 - {9, 10, 12}

2 - {3, 4}

3 -

我正在尝试使用锯齿状数组(我不知道是否有更好的方法来做到这一点,也许使用 ArrayList 或 Hashset 但我不确定)。

所以,要在锯齿状数组中插入数字,我将接收用户输入(2 个数字)。如果用户键入 1 和 2,我需要将两者都插入到锯齿状数组中。

但要做到这一点,我需要检查位置 0 是否为空,如果为空,我需要将用户输入放入锯齿状数组中。如果它不为空,那么它将检查输入是否存在于锯齿状数组中。

所以,我遇到的问题是检查锯齿状数组是否为空。

我试过了:

static void Main(string[] args)
    {
        Console.WriteLine("Digite a lista de numeros com um espaço de diferença entre cada numero");
        string[] ar_temp = Console.ReadLine().Split(' ');
        int[] ar = Array.ConvertAll(ar_temp, Int32.Parse);
        int tam = ar.Length;
        char fim = 's';


        int[][] jaggedarray = new int[tam / 2][];


        for (int x = 0; x < tam / 2; x++)
        {
            jaggedarray[x] = new int[tam];
        }

        if (jaggedarray[0] is null)
        {
            Console.WriteLine("is null");
        }
        else
        {
            Console.WriteLine("isn't null");
        }
    }

但我得到了错误的输出(它不将位置识别为空,即使那里有一个空数组......)

如何检查锯齿状数组的位置是否为空?

【问题讨论】:

  • 听起来你可能想要一个 List&lt;int&gt; 数组。
  • jaggedarray[0] is null?这甚至是合法的 C# 吗?
  • @WiktorZychla 这不会与 is null 一起编译。
  • @SamvelPetrosov:我知道,这是向 OP 提出的问题。
  • @WiktorZychla 我刚刚澄清了

标签: c# arrays jagged-arrays


【解决方案1】:

只需将is null 替换为== null,如下所示:

int[][] jaggedarray = new int[tam / 2][];

for(int x = 0; x < tam/2; x++)
{
    jaggedarray[x] = new int[tam];
}

if (jaggedarray[0] == null)
{
    Console.WriteLine("é nulo");
}
else
{
    Console.WriteLine("Não é nulo");
}

【讨论】:

  • 还是不行。它进入 else 条件。
  • 我现在明白了这个问题......问题是因为我在使用它之前初始化了数组内部的结构。感谢您的帮助!
【解决方案2】:

空数组不为空。您必须检查数组长度:

if (jaggedarray[0] == null || jaggedarray[0].Length == 0)
{
    Console.WriteLine("é nulo");
}
else
{
    Console.WriteLine("Não é nulo");
}

此外,您还可以简化代码:

Console.WriteLine(jaggedarray[0] == null || jaggedarray[0].Length == 0 ? "é nulo" : "Não é nulo");

【讨论】:

  • 它不工作。它返回给我位置内数组的大小......我的意思是,我需要为锯齿状数组中的每个数组指定一个大小以进行编译。因此,每个数组的大小为 4。该验证返回 4。我将使用完整代码编辑问题以便更好地理解。
  • 如果你总是初始化它,那么你需要一些标志列表来确定 jaggedarray[i] 是否被改变。另外,我稍微修正了我的答案。
  • 可以不初始化就使用锯齿状数组吗?
  • 是的,初始化数组本身,但不要在需要之前初始化 jaggedarray[x]。
猜你喜欢
  • 2010-11-08
  • 1970-01-01
  • 2011-09-13
  • 2020-09-11
  • 2014-05-16
  • 2011-06-10
  • 2015-01-03
  • 2013-08-14
  • 1970-01-01
相关资源
最近更新 更多