繁体   English   中英

控制台数组字符插入用户输入

[英]Console Array Char Insert User Input

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

您的逻辑在这里有点偏离。 在您的if语句中,您说的是“如果我的数组不为空”,则循环遍历其他数组(即您有一个空数组)“尝试插入该空数组”

您需要使用以下方法初始化数组:

private char[] currentMisses = new char[x]

x是您需要数组的大小。

我会改变这个:

private char[] currentMisses

对此:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM