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

3 回答 3

1

只需添加这个小改动!(添加else你的第二个条件)

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

之前发生的事情是您的控制台会读取一个 A 键并输入第一个条件。由于第二个和第三个条件与第一个是分开的,因此也将检查第二个条件,如果不为真(在这种情况下它不会为真),则无论输入 else 语句是什么。希望这可以帮助。

于 2020-03-15T23:06:11.493 回答
0

似乎程序正在完全按照您编写的方式执行。

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();
            }
于 2020-03-15T21:32:45.847 回答
0

如果你击中 A,它将排除 AD 的一部分。毕竟,A 等于 A,但 A 不等于 D。

你想要的可能是一个 switch/case 语句。

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

switch/case 语句和 do/while 循环 - 这两个是控制台程序流程的基础。

于 2020-03-15T21:32:52.877 回答