dimanche 5 décembre 2021

Console.ReadKey storing older keys and returning them after successful true return in c#

The code is pretty straightforward but not sure what the heck is going on. Any help is much appreciated.

I am a calling a validation function to check if user either entered 'c' or 'r' in Main method like this:

validation.ValidateInputChars(input, 'c', 'r');

and the validateInputChars function is like this:

public char ValidateInputChars(char actualInput, char input1, char input2)
       {
           if (char.Equals(actualInput, input1))
           {
               return 'c';
           }
           else if (char.Equals(actualInput, input2))
           {
               return 'r';
           }
           else
           {
               Console.WriteLine("\n You pressed " + actualInput + "\nYour input is incorrect, kindly press " + input1 + " or " + input2 + " to proceed");
               actualInput = Console.ReadKey().KeyChar;

               ValidateInputChars(actualInput, input1, input2);
               return 'z';
           }
       } 

The input is let's assume: 'q', 'w', 'e' and then 'c'.

It works all fine, until I press 'c'. It goes inside the first loop to return the correct input "c" but then the strange thing is it goes to the else loop as well, where the it's return 'z' 4 more times.

And at last the result it returns is the second input, so in this case it finally return 'w' (WTH!).

I've tried without if else statements, with List {'c', 'r'}, everything.

The only thins I need is to know if user entered 'c' or 'r' but it's not working.

Any Idea what's happening here?

Aucun commentaire:

Enregistrer un commentaire