【问题标题】:my shuffle string[] not working?我的随机字符串 [] 不起作用?
【发布时间】:2012-11-11 02:40:22
【问题描述】:

我试图编写一个随机字符串数组算法,但我得到一个空引用错误..我不知道为什么..

public static string[] arrRandomized;
public static string[] ShuffleWords(string[] Words)
{
    Random generator = new Random();
    for (int i=0;i < Words.Length; i++) {
        int pos = generator.Next(Words.Length);
        Console.WriteLine(Words[pos]); // I SEE RANDOM ITEM
        Console.Read(); // NULL REFERENCE ERROR AFTER THIS
        if (Words[pos] != null)
        {
            arrRandomized[i] = Words[pos];
            //remove item at pos so I get no duplicates
            Words[pos] = null;
        }
    }

我不想使用 ArrayList,我有我的理由,但那是题外话,我只是想知道这怎么不起作用:/ 谢谢

【问题讨论】:

  • 你在哪里使用 Console.Read() ?
  • 不建议在迭代时更改集合(或数组)。
  • “我不知道为什么..” 调试它。
  • 还要特别注意arrRandomized

标签: c# .net


【解决方案1】:

我认为你应该初始化arrRandomized:

arrRandomized = new string[Words.Length];

【讨论】:

    【解决方案2】:

    你的 arrRandomized 永远不会被初始化。我还建议您返回一个数组而不是使用静态引用,因为随后对该方法的调用将更改对 arrRandomized 的所有引用。

    public static string[] ShuffleWords(string[] Words)
    {    
        string[] arrRandomized = new string[Words.Length];
        Random generator = new Random();
        for (int i=0;i < Words.Length; i++) 
        {
            int pos = generator.Next(Words.Length);
            Console.WriteLine(Words[pos]); // I SEE RANDOM ITEM
            Console.Read(); // NULL REFERENCE ERROR AFTER THIS
            if (Words[pos] != null)
            {
                arrRandomized[i] = Words[pos];
                //remove item at pos so I get no duplicates
                Words[pos] = null;
            }
        }
        return arrRandomized;
    }
    

    【讨论】:

    • 消除了错误,但现在返回数组只有 2 项而不是 4 项。其他 2 项在那里但为空:/
    猜你喜欢
    • 2016-02-25
    • 1970-01-01
    • 2016-01-31
    • 1970-01-01
    • 1970-01-01
    • 2020-05-13
    • 1970-01-01
    • 2013-12-25
    • 2017-05-20
    相关资源
    最近更新 更多