C#查看是否输入了某个键

C# See If A Certain Key is Entered

我要创建的是一个 Magic 8 Ball。如果用户在提出问题之前要求摇动球,那么他们就会出错。如果他们提出问题(通过单击 A)然后要求摇动它(通过单击 S),他们将调用我的方法来摇动答案列表。我不想在这部分打印答案。

我遇到的问题是我不太确定如何查看用户是否输入了某个键。

namespace Magic8Ball_Console
{   

 class Program
    {
        static void Main(string[] args)
        {
        Console.WriteLine("Main program!");

        Console.WriteLine("Welcome to the Magic 8 Ball");
        Console.WriteLine("What would you like to do?");
        Console.WriteLine("(S)hake the Ball");
        Console.WriteLine("(A)sk a Question");
        Console.WriteLine("(G)et the Answer");
        Console.WriteLine("(E)xit the Game");
        Magic8Ball_Logic.Magic8Ball ball = new Magic8Ball_Logic.Magic8Ball();
        string input = Console.ReadLine().ToUpper();

        do
        {
            if (input == "S")
            {
                Console.WriteLine("Searching the Mystic Realms(RAM) for the answer");
                Console.ReadLine();
            }
            else if (input == "A") {
                //Call Method Shake()
                Console.ReadLine();
            }
        } while (input != "E");
    }
}
}

由于您已将用户输入读入变量输入,请检查其内容

string input = Console.ReadLine().ToUpper();
switch (input) {
    case "S":
        //TODO: Shake the Ball
        break;
    case "A":
        //TODO: Ask a question
        break;
    case "G":
        //TODO: Get the answer
        break;
    case "E":
        //TODO: Exit the game
        break;
    default:
       // Unknown input
       break;
}

请注意,如果您必须区分多种情况,通常使用 switch 比使用大量 if-else 语句更容易。

我将输入转换为大写,以便用户可以输入小写或大写命令。

如果您不想在处理完第一个命令后退出游戏,则必须使用一些循环。例如

do {
    // the code from above here
} while (input != "E");

另请参阅:switch (C# reference)