其他分享
首页 > 其他分享> > 控制台按键不起作用?

控制台按键不起作用?

作者:互联网

因此,我正在制作一个基于控制台的文字游戏,以了解更多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)它同时运行if&其他WriteLines,我假设与1)一起使用?

如何修改代码,以便在按“ y / Y”时读取正确的条件?或者,如何消除按Enter继续进行的需要?

解决方法:

在下面使用了您的代码,我对其进行了测试并成功运行.

我将char yes = Console.ReadKey()移到Console.WriteLine()下面.
我将名称= 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... ");
        }

标签:console-application,c
来源: https://codeday.me/bug/20191111/2022375.html