2

I am trying to create the menu for a mastermind game which can be ran in a command prompt using 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.

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.

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");
            }
        }
    }
}
prospector
  • 3,389
  • 1
  • 23
  • 40
Ben Reilly
  • 41
  • 5

3 Answers3

5

Console.ReadKey() returns a ConsoleKeyInfo object, which is not an int object. You can get a char from that, for example:

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

If you expect that char value to represent an integer, you can convert it to one:

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.

David
  • 208,112
  • 36
  • 198
  • 279
3

Console.ReadKey() returns a ConsoleKeyInfo, so you'll need to do something like this:

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");
}
Ousmane D.
  • 54,915
  • 8
  • 91
  • 126
0

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. But for this, a string works fine.

EpicKip
  • 4,015
  • 1
  • 20
  • 37