我正在编写一个代码,如果用户需要功能,则必须按“ y”或“ n”或输入“ yes”或“ no”,而无需检查是否区分大小写(因此它必须可以工作)如果用户输入是或是)。
同样,如果用户写了任何无效的东西,则表明该选项无效,并再次要求用户选择一个选项。
这是它的抽象:
static bool FeatureIsOn { get; set;}
static void Main()
{
bool optionIsValid;
do //Loops around until the option is valid
{
Console.WriteLine();
Console.Write("Enable Feature? [Y/N]: ");
string optionString = Console.ReadLine();
switch(optionString)
{
default:
Console.WriteLine("Invalid option.");
optionIsValid = false;
break;
case "Yes":
case "yes":
case "Y":
case "y":
FeatureIsOn = true;
optionIsValid = true;
break;
case "No":
case "no":
case "N":
case "n":
FeatureIsOn = false;
optionIsValid = true;
break;
}
} while (optionIsValid != true);
}
为每种可能的方式写“是”的情况不是很有效。有更好的方法吗?
在检查之前,将要检查的字符串转换为大写或小写:
static bool FeatureIsOn { get; set;}
static void Main()
{
bool optionIsValid;
do //Loops around until the option is valid
{
Console.WriteLine();
Console.Write("Enable Feature? [Y/N]: ");
string optionString = Console.ReadLine();
// convert string to uppercase
optionString = optionString.ToUpper();
switch(optionString)
{
case "YES":
case "Y":
FeatureIsOn = true;
optionIsValid = true;
break;
case "NO":
case "N":
FeatureIsOn = false;
optionIsValid = true;
break;
default:
Console.WriteLine("Invalid option.");
optionIsValid = false;
break;
}
} while (optionIsValid != true);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句