2015-10-15 3 views
0

Я добавил инициализацию, чтобы показать массив. Когда он попадает в другое и пытается вставить вход в массив, он выдает исключение. Я попробовал несколько разных примеров в Интернете и еще не нашел решения. Я благодарен за любую помощь, которая дается.Консоль Array Char Вставить пользовательский ввод

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- how-do-i-fix-it) –

+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] 
Смежные вопросы