Console Array Char Insert User Input

本文关键字:User Input Insert Char Array Console | 更新日期: 2023-09-27 18:17:59

我添加了初始化来显示数组。当它碰到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;                      
                }                 

Console Array Char Insert User Input

你的逻辑有点偏离。在if语句中你说"如果我的数组不为空"然后循环遍历数组else(即你有一个空数组)"try into the null array"

你需要这样初始化你的数组:

private char[] currentMisses = new char[x]

其中x是您需要的数组大小

我要改变这个:

private char[] currentMisses

to this:

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