C# C开关语句验证
我想知道在C中是否有这样的方法:C# C开关语句验证,c#,validation,switch-statement,C#,Validation,Switch Statement,我想知道在C中是否有这样的方法: some loop here { Console.WriteLine("Please enter a or b"); switch (Console.ReadLine().ToLower()) { case "a": //some code here break; case "b": //some code here
some loop here
{
Console.WriteLine("Please enter a or b");
switch (Console.ReadLine().ToLower())
{
case "a":
//some code here
break;
case "b":
//some code here
break;
default:
Console.WriteLine("Error, enter a or b");
repeat loop
}
}
这可能是一个愚蠢的问题,但类似的问题会对我的作业大有好处。为什么不呢。运行仅在输入a或b时存在的while循环
bool condition = false;
Console.WriteLine("Please enter a or b");
string str = string.Empty;
while (!condition)
{
str = Console.ReadLine().ToLower();
switch (str)
{
case "a":
//some code here
condition = true;
break;
case "b":
//some code here
condition = true;
break;
default:
Console.WriteLine("Error, enter a or b");
break;
}
}
Console.WriteLine("You have entered {0} ", str);
Console.ReadLine();
为什么不呢。运行仅在输入a或b时存在的while循环
bool condition = false;
Console.WriteLine("Please enter a or b");
string str = string.Empty;
while (!condition)
{
str = Console.ReadLine().ToLower();
switch (str)
{
case "a":
//some code here
condition = true;
break;
case "b":
//some code here
condition = true;
break;
default:
Console.WriteLine("Error, enter a or b");
break;
}
}
Console.WriteLine("You have entered {0} ", str);
Console.ReadLine();
像这样的怎么样
var acceptedValues = new List<string>()
{
"a",
"b",
};
Console.WriteLine("Please enter {0}", string.Join("or", acceptedValues));
var enteredValue = string.Empty;
do
{
enteredValue = Console.ReadLine().ToLower();
} while (!acceptedValues.Contains(enteredValue));
像这样的怎么样
var acceptedValues = new List<string>()
{
"a",
"b",
};
Console.WriteLine("Please enter {0}", string.Join("or", acceptedValues));
var enteredValue = string.Empty;
do
{
enteredValue = Console.ReadLine().ToLower();
} while (!acceptedValues.Contains(enteredValue));
请解释为什么投票被否决。迭代集合比使用switch语句要有效得多。我没有进行向下投票,但enteredValue没有超出while循环的范围?是的,很容易修复。谢谢你的回复。我甚至没有考虑这种选择。非常值得赞赏:switch语句在C中有其用途,但如果您的场景需要,集合可以是一个非常强大的工具。很高兴尽我所能提供帮助。请解释为什么这被否决。迭代集合比使用switch语句要有效得多。我没有进行向下投票,但enteredValue没有超出while循环的范围?是的,很容易修复。谢谢你的回复。我甚至没有考虑这种选择。非常值得赞赏:switch语句在C中有其用途,但如果您的场景需要,集合可以是一个非常强大的工具。很高兴尽我所能帮助你。