我是C#的新手.我在控制台应用程序中有一个"菜单".现在,当我完成从菜单中选择一个项目并执行该菜单项所需的操作时,我想循环并再次显示菜单,以便用户可以选择不同的菜单项.我在菜单上有一个退出,我只想用它退出.我尝试了一个while循环,但这不起作用.选择菜单项并运行所选项目代码后,它会关闭应用程序.我究竟做错了什么?
static void Main()
{
int input = 0;
while (true)
{
Console.WriteLine("MENU");
Console.WriteLine("Please enter the number that you want to do:");
Console.WriteLine("1. Do thing A");
Console.WriteLine("2. Do thing B");
Console.WriteLine("3. Do thing C");
Console.WriteLine("4. Do thing D");
Console.WriteLine("5. Do thing E");
Console.WriteLine("6. Do thing F");
Console.WriteLine("7. Exit");
int menuchoice = int.Parse(Console.ReadLine());
switch (menuchoice)
{
case 1:
Console.WriteLine("Thing A has been done");
break;
case 2:
Console.WriteLine("Thing B has been done");
break;
case 3:
Console.WriteLine("Thing C has been done");
break;
case 4:
Console.WriteLine("Thing D has been done");
break;
case 5:
Console.WriteLine("Thing E has been done");
break;
case 6:
Console.WriteLine("Thing F has been done");
break;
case 7:
Environment.Exit; //edit
break;
default:
Console.WriteLine("Sorry, invalid selection");
break;
}
input++;
if (input < 30)
continue;
else
break;
}
}
Run Code Online (Sandbox Code Playgroud)
有人可以帮忙吗?提前致谢!
编辑:我知道"Console.Exit"不起作用.我这样做就是为了说明控制台必须从那里退出.我的问题是,每次选择一个选项并运行所选的选项代码后,我每次都需要循环整个菜单.我只想用退出来退出.但此时菜单没有循环,控制台在选择了1个选项并且选项代码已经运行后关闭.
编辑:当你启动你的程序并按1然后按Return键会发生什么?这是真正的问题,菜单似乎没有循环.在我启动程序并按1后,返回代码1中的代码完美运行,然后控制台才关闭.如果我再次启动控制台并按下2,则情况2中的代码也会完美运行,但控制台再次关闭.我已经测试了所有这些情况,所有这些都运行得很好.
保持简单:循环保持循环直到按下7
int menuchoice = 0;
while (menuchoice != 7)
{
Console.WriteLine("MENU");
Console.WriteLine("Please enter the number that you want to do:");
Console.WriteLine("1. Do thing A");
Console.WriteLine("2. Do thing B");
Console.WriteLine("3. Do thing C");
Console.WriteLine("4. Do thing D");
Console.WriteLine("5. Do thing E");
Console.WriteLine("6. Do thing F");
Console.WriteLine("7. Exit");
menuchoice = int.Parse(Console.ReadLine());
switch (menuchoice)
{
case 1:
Console.WriteLine("Thing A has been done");
break;
case 2:
Console.WriteLine("Thing B has been done");
break;
case 3:
Console.WriteLine("Thing C has been done");
break;
case 4:
Console.WriteLine("Thing D has been done");
break;
case 5:
Console.WriteLine("Thing E has been done");
break;
case 6:
Console.WriteLine("Thing F has been done");
break;
case 7:
break; //edit
default:
Console.WriteLine("Sorry, invalid selection");
break;
}
Run Code Online (Sandbox Code Playgroud)