none
How do I get C# to refuse anything but 1 specific input? RRS feed

  • Question

  • Hello!

    I am new to C# and I was wondering how I could get C# to take only a specific set of inputs? I am working on a project and I need it to only accept 4 different values for a specific question otherwise the code repeats itself. The repeating is intended I just need it to accept 4 specific letters.

    Thursday, October 10, 2019 7:45 PM

All replies

  • Hi GlitchyBoi,

    I'm afraid your question is vague. 
    Could you provide your code in order for us to understand your issue?

    Regards,

    Ashidacchi -- https://ssl01.rocketnet.jp/hokusosha.com/default.html

    Thursday, October 10, 2019 10:55 PM
  • You should add more details what kind of an input are you talking about and what is the problem? But in general you define accepted inputs and then check if any of the user input is one of those. For example following code will ask user to press A, B, C, D until user presses one of them.

    ConsoleKey[] acceptKeys = new ConsoleKey[]
    {
        ConsoleKey.A,
        ConsoleKey.B,
        ConsoleKey.C,
        ConsoleKey.D
    };
    
    ConsoleKey userKey;
    
    do
    {
        Console.WriteLine("Press A, B, C or D:");
        userKey = Console.ReadKey().Key;
        Console.WriteLine();
    }
    while (Array.IndexOf(acceptKeys, userKey) < 0);
    
    // User pressed A, B C or D

    Friday, October 11, 2019 4:40 AM
  • Hi GlitchyBoi,

    Thank you for posting here.

    As all we said, your question is not clear.

    >>I need it to only accept 4 different values for a specific question otherwise the code repeats itself.

    I am not sure what you mean, what is your specific question and when the code repeats itself?

    It will be better for us to deal with your question if you tell me about it.

    Best Regards,

    Jack


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Friday, October 11, 2019 5:37 AM
    Moderator