简体   繁体   中英

c# menu in console application

Hi I'm trying to make a menu of instructions and I want to get the instruction number as an input to continue . here is my code :

 class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("please choose one of the numbers below : "+"\n");
        Console.WriteLine("1.adding new student"+"\n");
        Console.WriteLine("2.adding new course"+"\n");
        Console.WriteLine("3.adding new grade"+"\n");
        Console.WriteLine("4.showing the best student"+"\n");
        Console.WriteLine("5.getting students average"+"\n");
        Console.WriteLine("5.exit"+"\n");
        Console.ReadKey();
        if(ConsoleKey="1")
        {

        }

        Console.ReadKey();
    }

so how can I go to the next step if the user chooses number 1 for example? cause I know it's wrong to assign a number to Console.Readkey()

You can use Console.ReadLine() which gives you a string that you can validate / process in any way you want.

Anyway, you could also use the return value of Console.ReadKey()

It returns a ConsoleKeyInfo , so you can, for example do something like this:

if (Console.ReadKey().Key == ConsoleKey.D1) { /* key '1' pressed */ }

a full documentation of the ConsoleKey enum is here: https://msdn.microsoft.com/en-us/library/system.consolekey(v=vs.110).aspx

You are doing it the wrong way, you are not storing the value returned by the function call and that is why you cannot compare it's value at all. Secondly, as David has mentioned, you use == in C# and not = , which is an assignment operator. Consider using this,

// For this approach, you would have to limit the values to one character.
if(Console.ReadLine() == "1")
{
    // 1 was pressed
}

Otherwise use the following code,

if(Console.ReadKey().Key == ConsoleKey.D1)
{
    // 1 was pressed
}

A common example is to use Console.ReadKey() at the end of the program, to prevent the terminal from closing, and remember that data is lost . You can always compare the values and see which value was entered, for more go through the following,

  1. Console.ReadKey Method ()
  2. ConsoleKey Enumeration

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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