-1

I tried to write a shuffle string array algo but I get a null reference error.. I can't figure out why..

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

I don't want to use ArrayList, i have my reasons but thats off topic I just want to know how come this isn't working :/ thanks

7
  • 1
    Where are you using Console.Read() ? Commented Nov 10, 2012 at 18:22
  • Changing a collection (or array) while iterating over it is inadvisable. Commented Nov 10, 2012 at 18:23
  • 6
    "I can't figure out why.." Debug it. Commented Nov 10, 2012 at 18:23
  • Pay special attention to arrRandomized also. Commented Nov 10, 2012 at 18:27
  • stackoverflow.com/a/9558461/932418 Commented Nov 10, 2012 at 18:34

2 Answers 2

3

I think you should initialize arrRandomized:

arrRandomized = new string[Words.Length];
Sign up to request clarification or add additional context in comments.

Comments

0

Your arrRandomized is never intialized. I would also recommend that you return an array rather then use a static reference because the subsequent calls to the method will change all references to the 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;
}

1 Comment

got ridd of the error, but now the return array only has 2 items instead of 4.. the other 2 are there but empty :/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.