1

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();
}
  • 1
    I think you want an `else` right before `if (rollType.Key == ConsoleKey.D)`. Alternatively, you may use a [`switch` statement](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/switch). – 41686d6564 stands w. Palestine Mar 15 '20 at 21:32

3 Answers3

1

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.

A Bear
  • 59
  • 6
0

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();
            }
Pranav Negandhi
  • 1,594
  • 1
  • 8
  • 17
0

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.

Christopher
  • 9,634
  • 2
  • 17
  • 31