如何检查用户是否正确输入了命令 - C#

时间:2017-02-16 13:37:28

标签: c# console-application

我在C#的控制台应用程序中处理冒险类型的文本游戏。

我需要一种方法来测试用户是否正确输入了命令,以及他们是否还没有再次测试。

我现在正在尝试这个:

do
{
    Response = Console.ReadLine();
    switch (Response.ToLower())
    {
        case "hallway":
            Location = Locations[2];
            Console.WriteLine("You decide to get some fresh air, and step out of the dance room and into the hallway." + "\n" + "There's no one here.");
            Console.ForegroundColor = ConsoleColor.Cyan;
            Console.WriteLine("Command List: Look, Look at, Move, Check Status");
            Console.ResetColor();
            ResponseTester();
            break;
        case "dance room":
            //[Other code here]
            break;
        default:
            Console.WriteLine("I'm sorry, I don't understand that.");
            break;
    }
}
while (Response.ToLower() != "hallway" || Response.ToLower() != "dance room");

然而,它不是很可靠,因为当我尝试使用if / else语句或其他用途时,它只会测试一次。有没有更好的测试方法?

1 个答案:

答案 0 :(得分:0)

你需要按如下方式重写它

var invalid = true;
while (invalid )
{
  Response = Console.ReadLine();
  switch (Response.ToLower())
    {
      case "hallway":
      Location = Locations[2];
      Console.WriteLine("You decide to get some fresh air, and step out of the dance room and into the hallway." + "\n" + "There's no one here.");
      Console.ForegroundColor = ConsoleColor.Cyan;
      Console.WriteLine("Command List: Look, Look at, Move, Check Status");
      Console.ResetColor();
      ResponseTester();
      invalid = false;
      break;
    case "dance room":
      //[Other code here]
      invalid = false;
      break;
    default:
      Console.WriteLine("I'm sorry, I don't understand that.");
      break;
    }
  }

但除此之外,真正获得输入需要与处理游戏设计输入分开。设置一个可接受单词的数组或列表,然后对其进行测试,然后单独处理。

所以喜欢这个

private List<string> validWords = new List<string>{"hallway","dance room"};

private string GetInput()
{
  var response = string.Empty;
  while (true)
    {
      response = Console.ReadLine();
      if (validWords.Contains(response))
        {
          break;
        }
    }
    return response;
}

private void ProcessInput(string response)
{
   //switch statements go here
}