2015-10-15 78 views
0

我添加了初始化以显示数组。当它碰到else并尝试将输入插入到数组中时,它会引发异常。我在网上尝试了几个不同的例子,但还没有找到解决方案。我很感激任何帮助。控制台阵列字符插入用户输入

private char[] currentMisses; 

     public int makeTurn() 
    { 

     // Ask the user for a guess 
     Console.Write("Choose A Letter: "); 

     // Get the input from the user 

      var currentGuess = Console.ReadKey(); 
      char input = currentGuess.KeyChar; 
      input = Char.ToUpper(input); 

     // Do input conversions 
     while (!char.IsLetter(input)) 
       { 
        //Console.Write(input); 
        currentGuess = Console.ReadKey(true); 
        input = currentGuess.KeyChar; 
        input = Char.ToUpper(input); 
       } 

     // See if it exists in our word 
     bool test = false; 
     test = currentWord.Contains(input); 
     Console.WriteLine("Hello" + input); 


     // If we didn't find it 
     if (!test) 
      { 
       if (currentMisses != null) 
       { 
        Console.WriteLine("WORD"); 
        // Make sure it does not currently exist in the misses array 
        for (int i = 0; i < currentMisses.Length; i++) 
        { 
         if (currentMisses[i] != input) 
         { 
          currentMisses[i] = input; 
          Console.WriteLine("In Loop"); 
         } 
         Console.WriteLine("Not in Loop"); 
        } 
       } 
       else 
       { 
        /* This is where I am trying to insert the input from the user to the char array currentMisses, I've tried multiple ways and it seems simple but I hit a roadblock*/     
        currentMisses[0] = input;      
       }     
+1

您的数组未初始化。你试图插入一个零长度的数组 –

+0

可能的重复[什么是NullReferenceException,我该如何解决它?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-我怎么办 - 修复它) –

+0

你得到什么类型的错误? – BlackHatSamurai

回答

1

你的逻辑在这里有一点点。在你的if语句中你说“如果我的数组不是空的”然后遍历数组else(即你有一个空数组)“试图插入到该空数组”

你需要初始化你的数组如:

private char[] currentMisses = new char[x] 

其中x是你需要你的数组有多大。

1

我会改变这一点:

private char[] currentMisses 

这样:

int numberOfWrongGuessesAllowed = 10 //however many guess you allow user to make 
private char[] currentMisses = new char[numberOfWrongGuessesAllowed]