简体   繁体   English

主脑游戏的主菜单

[英]Main Menu for a mastermind game

I am trying to create the menu for a mastermind game which can be ran in a command prompt using C#. 我正在尝试为主题游戏创建菜单,可以使用C#在命令提示符下运行。 The issue I am running into is capturing the users input for the menu. 我遇到的问题是捕获菜单的用户输入。 If they enter a 2 then it should display that they entered the number two and if not then it would say they have not displayed the number two. 如果他们输入2然后它应该显示他们输入了第二个,如果没有,那么它会说他们没有显示第二个。

The issue I am having is that it wont turn the users input into a working integer and will either come up saying that it can't explicitly convert from System.ConsoleKeyInfo to int or string to int. 我遇到的问题是它不会将用户输入转换为工作整数,并且要么说它不能显式地从System.ConsoleKeyInfo转换为int或字符串转换为int。

using System;

namespace MasterMind
{
    class Program
    {
        static void Main(string[] args)
        {

            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("               MasterMind's Main Menu");
            Console.WriteLine("                    1: Play");
            Console.WriteLine("                    2: Help");
            Console.WriteLine("                    0: Exit");
            int userinput = Console.ReadKey();
            if (Nuserinput == 2);
            {
                Console.WriteLine("This is a number 2");
            }
            else
            {
                Console.WriteLine("This is not a number 2");
            }
        }
    }
}

Console.ReadKey() returns a ConsoleKeyInfo object , which is not an int object. Console.ReadKey() 返回一个ConsoleKeyInfo对象 ,该对象不是int对象。 You can get a char from that, for example: 您可以从中获取一个char ,例如:

var key = Console.ReadKey();
var keyChar = key.KeyChar;

If you expect that char value to represent an integer, you can convert it to one: 如果您希望char值表示整数,则可以将其转换为1:

int keyInt = (int)Char.GetNumericValue(keyChar);

Aside from other error checking you might want to put in place in case the user doesn't enter a valid integer, this would at least get your the integer value you're looking for. 除了其他错误检查之外,您可能希望在用户输入有效整数的情况下放置,这至少会获得您正在寻找的整数值。

Console.ReadKey() returns a ConsoleKeyInfo , so you'll need to do something like this: Console.ReadKey()返回一个ConsoleKeyInfo ,因此您需要执行以下操作:

ConsoleKeyInfo data = Console.ReadKey();
int num;
if (int.TryParse(data.KeyChar.ToString(), out num) && num == 2)
{
    Console.WriteLine("This is a number 2");
}else{
    Console.WriteLine("This is not a number 2");
}

Change your 改变你的

int userinput = Console.ReadKey();
if (Nuserinput == 2)

To: 至:

string userInput = Console.ReadKey().KeyChar.ToString();
if(input == "2")

Or covert the string to an int as shown in other answers. 或者将字符串转换为int,如其他答案所示。 But for this, a string works fine. 但为此,字符串工作正常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM