【问题标题】:C# See If A Certain Key is EnteredC#查看是否输入了某个键
【发布时间】:2019-05-04 17:54:56
【问题描述】:

我正在尝试创建的是一个 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");
    }
}
}

【问题讨论】:

  • 从现在开始,您正在显示更正后的代码,这会使您的问题和我的回答无效。请把它恢复到原来的那个。删除 if 中的ReadLine()。相反,将行 string input = Console.ReadLine().ToUpper(); 移动到循环内(作为第一条语句)。

标签: c# user-input keypress


【解决方案1】:

既然你已经将用户输入读入变量输入,请检查其内容

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)

【讨论】:

    猜你喜欢
    • 2017-05-26
    • 2018-05-02
    • 2012-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-13
    • 1970-01-01
    相关资源
    最近更新 更多