简体   繁体   中英

Console.ReadKey seems to be reading the wrong key?

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();
}

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.

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();
            }

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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