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

Time:12-06

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?

CodePudding user response:

It seems that you want ask user again and again until correct character is provided. If it's your case then you should put

 // validate actualInput again, return a valid choice
 return ValidateInputChars(actualInput, input1, input2);

instead of

// Validate, ignore valid choice and...
ValidateInputChars(actualInput, input1, input2);

// ...return 'z' (!) 
return 'z';

And, please, avoid magic consts like 'c', 'r':

 if (char.Equals(actualInput, input1))
 {
     return input1; // there's no guarantee, that input1 == 'c' 
 }
 if (char.Equals(actualInput, input2))
 {
     return input2; // there's no guarantee, that input2 == 'r' 
 }

I'd rather get rid of recursion in favor of a simple while loop:

// static: we don't want "this" in the method
public static char ValidateInputChars(char actualInput, char input1, char input2) {
  // while actualInput is NOT correct, keep asking user  
  while (actualInput != input1 && actualInput != input2) {
    Console.WriteLine($"\n You pressed {actualInput}\nYour input is incorrect, kindly press {input1} or {input2} to proceed");

    actualInput = Console.ReadKey().KeyChar;
  }   

  return actualInput; 
}
  • Related