Console.ReadKey seems to be reading the wrong key?

228 Views Asked by At

I'm just starting out so I'm in the middle of writing my first console application from scratch. I have this line of code, when I hit d it correctly takes me to the next step and sets disadvantage to true, however if I hit a it executes the else statement for some reason. Any ideas what the cause is?

Console.WriteLine("Press the A key for advantage, or the D key for disadvantage");
var rollType = Console.ReadKey();
Console.WriteLine(System.Environment.NewLine);
if (rollType.Key == ConsoleKey.A)
{
    advantage = true;
}
if (rollType.Key == ConsoleKey.D)
{
    disadvantage = true;
}
else
{
    Console.WriteLine("Invalid Input");
    StartApp();
}
3

There are 3 best solutions below

0
A Bear On BEST ANSWER

Just add make this small change! (Adding else in your second conditional)

if (rollType.Key == ConsoleKey.A)
{
    advantage = true;
}
else if (rollType.Key == ConsoleKey.D)
{
    disadvantage = true;
}
else
{
    Console.WriteLine("Invalid Input");
    StartApp();
}

What was happening before is your Console would read an A key and enter the first conditional. Since the second and third conditional was separate from the first, the second would also be checked and if not true (which in this case it would not be true) it would no matter what enter the else statement. Hope this helps.

0
Pranav Negandhi On

Seems like the program is being executed exactly as you’ve written it to.

if (rollType.Key == ConsoleKey.A)
            {
                advantage = true;
            } // First conditional check ends here

// This is another conditional block
            if (rollType.Key == ConsoleKey.D)
            {
                disadvantage = true;
            }
            else // You pressed A, so this block is executed
            {
                Console.WriteLine("Invalid Input");
                StartApp();
            }
0
Christopher On

If you hit A, it will excude A and else part of D. After all, A equals A but A does not equal D.

What you want is propably a switch/case statement.

switch(rollType){
case ConsoleKey.A:
  advantage = true;
  break;
case ConsoleKey.D:
  disadvantage = true;
  break;
default:
  Console.WriteLine("Invalid Input");
  break;
}

switch/case statement and do/while loop - these two are the fundament of console programm flow.