简体   繁体   English

C#如何使开关忽略无效输入?

[英]C# How do I make a switch ignore invalid input?

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. 用户输入新游戏的“ N”,加载游戏的“ L”或退出的“ E”。 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. 我已经用Google搜索了这个问题,但是没有找到答案。 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. 我在发布代码中没有多大意义,因为简单切换10行可能对解决问题没有太大帮助。 Also, if there would be an easier / more efficient way than a switch, I would love to know. 另外,如果有比开关更简单/有效的方法,我很想知道。

Thanks. 谢谢。

You can use a default: statement to handle the other (unknown) cases: 您可以使用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;
}

Anything not specified in one of your other cases will fall into the default case, which you can then use to prompt for valid input. 在您的其他情况下未指定的任何内容都将属于default情况,然后您可以使用该default情况来提示输入有效的内容。

If you want to actually ignore all keys other than valid ones you could do something like this: 如果您实际上想忽略除有效密钥以外的所有其他密钥,则可以执行以下操作:

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.
        }
    }
}

When you use ReadKey(true) the true indicated that it will intercept that key and not display it on the console. 当您使用ReadKey(true)true表示它将拦截该键,而不在控制台上显示它。 This gives you the option of determining if it's valid or invalid. 这使您可以选择确定其有效还是无效。

如果switch语句没有default块,并且如果打开的表达式不匹配任何case块,则switch语句不执行任何操作。

When you have only 3 cases, a switch isn't much more efficient than just a simple if-else construct. 当只有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.

If you insist on using a switch, then your construct is very similar: 如果您坚持使用开关,那么您的构造非常相似:

switch (input)
{
    case "N":
        //New Game
        break;
    case "L":
        //Load Game
        break;
    case "E":
        //Exit Game
        break;
    default:
        //Do nothing (ignore unmatched inputs)
        break;
}

Thanks for the replies, guys. 伙计们,谢谢你的答复。 I managed to solve the problem by doing the following: 通过执行以下操作,我设法解决了该问题:

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;

        }
    }

I'm not sure how 'proper' this is, but it does what I need it to do. 我不确定这有多“合适”,但是它确实满足了我的需要。 Any keys other than 'N', 'L', and 'E' no longer do anything. 除“ N”,“ L”和“ E”以外的任何键均不再起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM