C# 我的洗牌字符串[]不工作?
我试图编写一个随机字符串数组算法,但得到一个空引用错误。。我不明白为什么C# 我的洗牌字符串[]不工作?,c#,.net,C#,.net,我试图编写一个随机字符串数组算法,但得到一个空引用错误。。我不明白为什么 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.
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;
}
}
公共静态字符串[];
公共静态字符串[]ShuffleWords(字符串[]字)
{
随机生成器=新随机();
for(int i=0;i
我不想使用ArrayList,我有我的理由,但那是离题的,我只想知道这是怎么不起作用的:/Thank我想你应该初始化
ArrayList
:
arrRandomized = new string[Words.Length];
您的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;
}
publicstaticstring[]ShuffleWords(string[]Words)
{
string[]arrraminated=新字符串[Words.Length];
随机生成器=新随机();
for(int i=0;i
您在哪里使用Console.Read()?在对集合(或数组)进行迭代时更改集合(或数组)是不可取的。“我不知道为什么…”调试它。还要特别注意arrrambiated
也。已经消除了错误,但现在返回数组只有2项,而不是4项。其他2项在那里,但为空:/