C#查看是否输入了某个键
我想创造的是一个神奇的8号球。如果用户在提问前要求摇动球,则会出现错误。如果他们问问题(通过点击A),然后要求摇动它(通过点击S),他们将调用我的方法来摇动答案列表。我不想打印这部分的答案 我遇到的问题是,我不太确定如何查看用户是否输入了某个密钥C#查看是否输入了某个键,c#,user-input,keypress,C#,User Input,Keypress,我想创造的是一个神奇的8号球。如果用户在提问前要求摇动球,则会出现错误。如果他们问问题(通过点击A),然后要求摇动它(通过点击S),他们将调用我的方法来摇动答案列表。我不想打印这部分的答案 我遇到的问题是,我不太确定如何查看用户是否输入了某个密钥 namespace Magic8Ball_Console { class Program { static void Main(string[] args) { Console.Writ
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");
另请参见:因为现在,您正在显示更正的代码,这将使您的问题和我的答案无效。请恢复原样。删除if中的
ReadLine()
。相反,移动行string input=Console.ReadLine().ToUpper()循环内的代码>作为第一条语句。