C#循环搜索字符不起作用

时间:2017-10-02 11:41:04

标签: c# arrays loops for-loop indexing

我有一个循环搜索用户输入的字符转换器的索引到一个char数组与秘密字相比,虽然它确实循环它的单词多长时间它仍然没有进入我的消息框(这是用于调试以检查它是否工作)。我也不知道如何透露一封信。

private void guessBtn_Click(object sender, EventArgs e)
{
    char[] randomCharArray = randomInput.ToLowerInvariant().ToCharArray();
    char[] userInputArray = userInput.ToLowerInvariant().ToCharArray();
    for (int i = 0; i < randomCharArray.Length; i++)
    {
        if (randomCharArray[i] == userInputArray[i])
        {
            MessageBox.Show("Hi");
        }
    }
}

private void resetGamebtn_Click(object sender, EventArgs e)
{
    SetUpWords();
}

private void SetUpWords()
{
    string path = (@"C:\commonwords.txt"); // Save the variable path with the path to the txt file
    words = File.ReadAllLines(path);
    int guessIndex = (new Random()).Next(words.Length);
    currentWord = words[guessIndex];

    for (int i = 0; i < currentWord.Length; i++)
    {
        wordlbl.Text += "*";
    }
}

1 个答案:

答案 0 :(得分:0)

如果randomInput和userInput是文本框,则忘记.Text获取字符串值。

试试这个:

char[] randomCharArray = randomInput.Text.ToLowerInvariant().ToCharArray();
char[] userInputArray = userInput.Text.ToLowerInvariant().ToCharArray();

而不是:

char[] randomCharArray = randomInput.ToLowerInvariant().ToCharArray();
char[] userInputArray = userInput.ToLowerInvariant().ToCharArray();

在评论中提供更多信息后进行编辑:

索引超出异常是由于randomCharArray大于userInputChar。

2电位解决方案:

    private void guessBtn_Click(object sender, EventArgs e)
    {
        char[] randomCharArray = randomInput.ToLowerInvariant().ToCharArray();
        char[] userInputArray = userInput.ToLowerInvariant().ToCharArray();
        //Assume that userInput would never be superior than randomCharArray
        //And contain only one char
        for (int i = 0; i < randomCharArray.Length; i++)
        {
            if (randomCharArray[i] == userInputArray[0])
            {
                MessageBox.Show("Hi");
            }
        }
       // Clean userInput in form
       userInputBox.Text = "";
    }

    private void guessBtn_Click(object sender, EventArgs e)
{
    char[] randomCharArray = randomInput.ToLowerInvariant().ToCharArray();
    char[] userInputArray = userInput.ToLowerInvariant().ToCharArray();
    // userInput can be equal to randomCharArray but running is more longer

    for (int i = 0; i < randomCharArray.Length; i++)
    {
      for(int j = 0; j < userInputArray.Length; j++){
        if (randomCharArray[i] == userInputArray[j])
        {
            MessageBox.Show("Hi");
        }
      }
    }
}