0

I am trying to make a simple console game that starts with a title screen. The user inputs 'N' for a new game, 'L' to load a game, or 'E' to exit. I have this set up as a switch, but I need to know how to make the program ignore any input other than the aforementioned keys. I've Googled this question but didn't find an answer. Please help if you can.

I don't see much point in posting the code as 10 lines of a simple switch probably wouldn't be terribly helpful to solving the problem. Also, if there would be an easier / more efficient way than a switch, I would love to know.

Thanks.

4

5 回答 5

3

您可以使用default:语句来处理其他(未知)情况:

switch(inputString.ToLower())
{
     case "n":
       // Handle new
       break;
     //.. handle known cases
     default:
         Console.WriteLine("Unknown option chosen.  Please enter valid option:");
         // Re-read values, etc?
         break;
}

在您的其他案例之一中未指定的任何内容都将属于该default案例,然后您可以使用它来提示有效输入。

于 2012-10-22T17:59:13.427 回答
1

如果您想实际忽略除有效键之外的所有键,您可以执行以下操作:

public static char ReadKey(IEnumerable<char> validKeys)
{
    var validKeySet = new HashSet<char>(validKeys);
    while (true)
    {
        var key = Console.ReadKey(true);
        if (validKeySet.Contains(key.KeyChar))
        {
            //you could print it out if you wanted.
            //Console.Write(key.KeyChar);
            return key.KeyChar;
        }
        else
        {
            //you could print an error message here if you wanted.
        }
    }
}

当您使用指示时,它将拦截该密钥并且不会将其显示在控制台上ReadKey(true)true这使您可以选择确定它是有效的还是无效的。

于 2012-10-22T18:03:34.797 回答
0

如果一个switch语句没有default块,并且如果被打开的表达式不匹配任何case块,则该switch语句什么也不做。

于 2012-10-22T18:01:03.940 回答
0

感谢您的回复,伙计们。我设法通过执行以下操作来解决问题:

static void titleInput()
    {
        ConsoleKeyInfo titleOption = Console.ReadKey(true);

        switch (titleOption.Key)
        {
            case ConsoleKey.N:
                Console.Clear();
                break;
            case ConsoleKey.L:
                break;
            case ConsoleKey.E:
                Environment.Exit(0);
                break;
            default:
                titleInput();
                break;

        }
    }

我不确定这有多“正确”,但它可以满足我的需要。除了“N”、“L”和“E”之外的任何键都不再执行任何操作。

于 2012-10-22T18:33:28.690 回答
0

当您只有 3 个案例时,开关并不比简单的if-else构造更有效。

if (input == "N")
{
    // New game
}
else if (input == "L")
{
    // Load game
}
else if (input == "E")
{
    // Exit game
}
// if none of the cases match, the input is effectively ignored.

如果您坚持使用开关,那么您的构造非常相似:

switch (input)
{
    case "N":
        //New Game
        break;
    case "L":
        //Load Game
        break;
    case "E":
        //Exit Game
        break;
    default:
        //Do nothing (ignore unmatched inputs)
        break;
}
于 2012-10-22T18:03:22.677 回答