我试图弄清楚如何在控制台应用程序的循环结束时接受来自用户的输入以重新执行循环或不使用 Y/N 问题。
问问题
1457 次
6 回答
4
bool executeLoop = true;
while (executeLoop)
{
...
Console.WriteLine("Again? (Y/N)");
string input = Console.ReadLine().ToUpper();
while (input != "N" && input != "Y")
{
Console.WriteLine("Invalid answer. Again? (Y/N)");
input = Console.ReadLine();
}
if (input == "N")
{
executeLoop = false;
// can also just write "break;"
}
}
这部分验证答案是 Y 还是 N:
while (input != "N" && input != "Y")
{
Console.WriteLine("Invalid answer. Again? (Y/N)");
input = Console.ReadLine();
}
您还可以删除该部分,以便“N”以外的每个输入都将继续循环。
另一种简单的方法是:
while (true)
{
...
Console.WriteLine("Enter \"Y\" to continue...");
if (Console.ReadLine().ToUpper() != "Y")
{
break;
}
}
这样循环将一直执行,直到用户输入“Y”以外的任何内容。
于 2012-09-24T03:54:58.360 回答
3
用于Console.ReadKey
从用户获取关键输入:
while (true)
{
Console.Write("End program Y/N: ");
char input = Console.ReadKey().KeyChar;
if (input == 'Y' || input == 'y') break;
Console.WriteLine();
}
于 2012-09-24T03:57:36.340 回答
0
做一个 do while 循环。
do
{
//do other stuff first
//then get input to Y and N question and set it
} while (input == 'Y');
于 2012-09-24T03:52:46.400 回答
0
那这个呢
string s;
do
{
// some statements
s = Console.ReadLine();
} while(s=="yes");
于 2012-09-24T03:55:23.170 回答
0
当你想跳出一个循环时,你可以使用“break”命令。请注意,每个中断只会让您脱离您所处的最小循环。
int count = 0;
string myentry = "";
for (count = 1; count < 10; count++)
{
Console.WriteLine("count=" + count);
Console.WriteLine("Continue? Enter \"Y\" or \"N\"");
myentry = Console.ReadLine().ToUpper();
if (myentry=="N")
{
break;
}
}
于 2012-09-24T04:02:11.030 回答
0
do
{
if(!somecondition){ continue; }
DoSomething();
Console.WriteLine("Do something again? (y = yes)");
}
while(Console.ReadKey().Key == ConsoleKey.Y);
于 2012-09-24T04:39:58.740 回答