我的shuffle string []无法正常工作?

时间:2012-11-10 18:19:41

标签: c# .net

我试着写一个shuffle字符串数组算法,但是我得到一个空引用错误..我无法弄清楚为什么..

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,我有我的理由,但那是关于主题我只是想知道为什么这不起作用:/谢谢

2 个答案:

答案 0 :(得分:3)

我认为你应该初始化arrRandomized

arrRandomized = new string[Words.Length];

答案 1 :(得分:0)

您的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;
}