我正在尝试确定让以下代码迭代的最佳方法,直到用户输入有效数字(1-6)。只要用户输入的数字大于6,程序就应该继续提示用户输入有效数字。
static void Main(string[] args)
{
string favoriteBand;
Console.WriteLine("What is your favorite rock band?");
Console.WriteLine("");
Console.WriteLine("1.) Journey");
Console.WriteLine("2.) Boston");
Console.WriteLine("3.) Styx");
Console.WriteLine("4.) Kansas");
Console.WriteLine("5.) Foreigner");
Console.WriteLine("Press 6 to exit the program.");
Console.WriteLine("");
favoriteBand = (Console.ReadLine());
switch (favoriteBand)
{
case "1": Console.WriteLine("Don't Stop Believin'!"); break;
case "2": Console.WriteLine("More Than a Feeling!"); break;
case "3": Console.WriteLine("Come Sail Away!"); break;
case "4": Console.WriteLine("Dust in the Wind!"); break;
case "5": Console.WriteLine("Hot Blooded!"); break;
case "6": return;
default: Console.WriteLine("Error, invalid choice. Please choose a valid number."); break;
}
Console.WriteLine("Press any key to continue.");
Console.ReadKey();
}
如何让这个程序继续使用循环提示输入有效数字?
答案 0 :(得分:3)
只是为了好玩,我们可以在这里取下开关
(仅仅有6个案例的简单开关并不需要)
bool isValid = true;
Dictionary<string, Action> command = new Dictionary<string, Action>();
command.Add("1", () => {Console.WriteLine("Don't Stop Believin'!");isValid = false;});
command.Add("2", () => {Console.WriteLine("More Than a Feeling!");isValid = false;});
command.Add("3", () => {Console.WriteLine("Come Sail Away!");isValid = false;});
command.Add("4", () => {Console.WriteLine("Dust in the Wind!");isValid = false;});
command.Add("5", () => {Console.WriteLine("Hot Blooded!");isValid = false;});
command.Add("6", () => isValid = false);
while(isValid)
{
string line = Console.ReadLine();
if(command.Keys.Contains(line))
command[line].Invoke();
else
Console.WriteLine("Choose from 1 to 6");
}
答案 1 :(得分:2)
将bool
变量与while
bool control = true;
while(control)
{
favoriteBand = (Console.ReadLine());
switch (favoriteBand)
{
case "1": Console.WriteLine("Don't Stop Believin'!"); control = false;break;
case "2": Console.WriteLine("More Than a Feeling!");control = false; break;
case "3": Console.WriteLine("Come Sail Away!"); control = false;break;
case "4": Console.WriteLine("Dust in the Wind!"); control = false;break;
case "5": Console.WriteLine("Hot Blooded!"); control = false;break;
case "6": control = false; break;
default: Console.WriteLine("Error, invalid choice. Please choose a valid number."); break;
}
}