gpt4 book ai didi

c# - 控制台按键不起作用?

转载 作者:行者123 更新时间:2023-11-30 15:59:13 25 4
gpt4 key购买 nike

所以我正在制作一个基于控制台的文本游戏来学习更多 C#,但我现在陷入困境并求助于 SO。

这可能是一个显而易见的答案,但我需要另一双眼睛来帮助我。我已经检查了这里的其他问题,但它们似乎对我没有帮助。

在我的 Main() 中,我有以下内容:

        int age;

Console.Write("Before entering the unknown, could you please confirm your age? ");
age = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("");

if (age < 18)
{
Console.WriteLine("I'm sorry, you'll now be transferred to a non-explicit version.");
Console.WriteLine("\n<Press any key to continue>");
Console.ReadKey();
Console.Write("\nPlease wait...");
for (int t = 5; t >= 0; t--)
{
Console.CursorLeft = 22;
Console.Write("{0:00}" + " seconds remaining", t);
Thread.Sleep(1000);
}
Console.WriteLine("");
Console.WriteLine("\nTo proceed, please press any key...");
Console.ReadLine();

NonExplicit();
}

不言自明。一旦它遇到 NonExplicit() 方法,就会调用以下内容:

        char yes = Console.ReadKey().KeyChar;
string name;

Console.WriteLine("\nYou're awake? It's about time. Not old enough, eh? That sucks. \n\nListen, I really need your help. Would you be interested? Y / N");
Console.ReadKey();

if (yes == 'y' || yes == 'Y')
{
Console.Write("\nYou will?! Wow, That's fantastic. Right then, where shall I start? \nI know! How about telling me your name? ");
name = Console.ReadKey().ToString();
Console.WriteLine("\nAhh yes, now you mention it, I certainly remember you, {0}!", name);
}
else
{
Console.WriteLine("\nYou don't want to help me? Oh, that's unfortunate... ");
}

似乎发生的是,当按下“y”或“Y”时:

1) 注册以上需要按回车键

2) 它同时运行 ifelse WriteLines,我假设它与 1) 一起运行?

如何修改我的代码,以便在按下“y/Y”时读取正确的条件?或者我怎样才能消除按下 Enter 键才能继续的需要?

最佳答案

在下面使用了您的代码,我对其进行了测试并且有效。

我将 char yes = Console.ReadKey() 移到了 Console.WriteLine() 下面。
我将 name = Console.ReadKey() 更改为 Console.ReadLine() 因为名称不止 1 个键。

        string name;
Console.WriteLine("\nYou're awake? It's about time. Not old enough, eh? That sucks. \n\nListen, I really need your help. Would you be interested? Y / N");
char yes = Console.ReadKey();

if (yes == 'y' || yes == 'Y')
{
Console.Write("\nYou will?! Wow, That's fantastic. Right then, where shall I start? \nI know! How about telling me your name? ");
name = Console.ReadLine();
Console.WriteLine("\nAhh yes, now you mention it, I certainly remember you, {0}!", name);
Console.ReadKey(); // I put this here so the program wouldn't exit
}
else
{
Console.WriteLine("\nYou don't want to help me? Oh, that's unfortunate... ");
}

关于c# - 控制台按键不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41869673/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com