[英]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?例如,如果用户选择数字 1,我该如何进行下一步? cause I know it's wrong to assign a number to Console.Readkey()
因为我知道为 Console.Readkey() 分配一个数字是错误的
You can use Console.ReadLine()
which gives you a string
that you can validate / process in any way you want.您可以使用
Console.ReadLine()
它为您提供一个string
,您可以以任何您想要的方式验证/处理。
Anyway, you could also use the return value of Console.ReadKey()
无论如何,您也可以使用
Console.ReadKey()
的返回值
It returns a ConsoleKeyInfo
, so you can, for example do something like this:它返回一个
ConsoleKeyInfo
,因此您可以执行以下操作:
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 ConsoleKey
枚举的完整文档在这里: https : ConsoleKey
( v= ConsoleKey
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.其次,正如 David 所提到的,您在 C# 中使用
==
而不是=
,后者是一个赋值运算符。 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 .一个常见的例子是在程序末尾使用
Console.ReadKey()
,防止终端关闭,并记住数据丢失。 You can always compare the values and see which value was entered, for more go through the following,您始终可以比较这些值并查看输入了哪个值,有关更多信息,请参阅以下内容,
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.