我正在尝试编写一个程序来跟踪我在游戏中死亡的次数。该程序将运行,接受用户输入并跟踪信息。当我运行该程序时,它可以工作,但是您只能输入一个键。例如,如果您启动它,然后按“ D”,它将在“死亡”变量中添加一个,但是您将无法键入其他任何内容。这是代码:
Console.WriteLine(
"To add one to Deaths stat, press D. To add one to Charms Stat, press C. " +
"To see all stats, press S.");
int deaths = 0;
int charms = 23;
ConsoleKeyInfo datKey;
datKey = Console.ReadKey();
if (datKey.Key == ConsoleKey.D)
{
deaths = deaths + 1;
Console.WriteLine();
Console.WriteLine("Death Added");
}
if (datKey.Key == ConsoleKey.C)
{
charms = charms + 1;
Console.WriteLine();
Console.WriteLine("Charm Added");
}
if (datKey.Key == ConsoleKey.S)
{
Console.WriteLine();
Console.WriteLine($"You have {charms} charms \nYou have died {deaths} times");
答案 0 :(得分:3)
尝试一下:
using System;
namespace TestApp
{
class Program
{
static void Main()
{
Console.WriteLine("To add one to Deaths stat, press D. To add one to Charms Stat, press C (like you'll have to use that one). To see all stats, press S.");
int deaths = 0;
int charms = 23;
ConsoleKeyInfo datKey;
do
{
datKey = Console.ReadKey();
switch(datKey.Key)
{
case ConsoleKey.D:
deaths++;
Console.WriteLine();
Console.WriteLine("Death Added");
break;
case ConsoleKey.C:
charms++;
Console.WriteLine();
Console.WriteLine("Charm Added");
break;
case ConsoleKey.S:
Console.WriteLine();
Console.WriteLine($"You have {charms} charms \nYou have died {deaths} times sence starting this program");
break;
default:
Console.WriteLine();
Console.WriteLine("A useless key pressed");
break;
}
} while (datKey.Key != ConsoleKey.S);
Console.ReadKey();
}
}
}
如您所见,我已经将您的用户输入请求(datKey = Console.ReadKey();)封装在一个循环中,因此程序将继续要求用户键入键。只有用户键入S,循环才会中断。此外,我已将您的许多if语句更改为切换结构,在这种情况下最好使用