检查用户输入是否已输入

时间:2016-06-13 12:02:09

标签: c# if-statement console-application

我试图让用户输入一个字符并检查他们之前是否输入了该字符。如果发生这种情况,请让他输入他以前没用过的另一个字符。我的知识仅限于if语句和循环,所以如果解决方案是我能理解的,我会很感激。

当我输入任何字母,例如E时,它会将其抛入猜测数组中,如果我再次输入E,它会再次投入猜测数组,而不是要求用户更改字母。

string check= "";
char wguess ='';
char[] wguess = new char[26];
do
{
    check = Console.ReadLine();

    if (check!="")
    {
        wguess = char.ToUpper(Convert.ToChar(check));
        for (int i = 0; i <= 25; i++)
        {
            if (wguess == guessed[i])
            {
                Console.Write(wguess);
                Console.WriteLine(guessed[i]);
                Console.WriteLine("Please choose a letter you haven't used yet.");
            }
            else
            {
                Console.Write(wguess);
                Console.WriteLine(guessed[i]);
                temp = wguess;
                guessed[i] = wguess;
                wguess = ' ';
            }
        }
    }
    else
    {
        Console.WriteLine("Please Enter a letter.");
    }
} while (check=="");
  

输出1 =猜测字母:E

     

输出2 =猜测字母:EE

2 个答案:

答案 0 :(得分:1)

您可以使用Contains方法,如下所示:

  If(guessed.Contains(wguess)
    { 
       //Whatever happens when the character already has been entered
    }
    else
    {
      //Whatever happens when the character has not been guessed
    }

答案 1 :(得分:0)

更改以下代码:

do{
    check = char.ToUpper(Convert.ToChar(Console.ReadKey()));
    if (!guessed.Contains(check))
    {
        // This is new, not in the guessed
    }
    else 
    { 
    // Already entered
    }

} while (check==' ');