如果 Console.ReadLine() 与定义的输入匹配,我如何忽略'while-loop' + 无效输入时仅循环一次



我告诉用户键入三种可能的颜色之一。如果用户错误地键入颜色(拼写等( - "while"功能应重复,直到他们键入"有效"颜色。

"while"函数似乎只运行一次,然后无论用户键是什么,都会继续运行。

它似乎也忽略了用户首先键入的任何内容(即使它是正确的(并输入"while"功能。如果用户第一次选择正确,我显然希望它一起跳过"while"功能。

*由于一些不正确的(OLD(代码仍然存在,因此编辑了示例 下面的代码示例...

Console.WriteLine("Select Colour (Red / Blue / Green): ");
string colSel = Console.ReadLine().ToLower();
while (colSel != "Red" || colSel != "Blue" || colSel != "Green")
{
Console.WriteLine("Sorry, I didn't catch that...");
Console.Write("Select Colour (Red / Blue / Green): ");
colSel = Console.ReadLine().ToLower();
break;
}
Console.WriteLine("Alright " + colSel + ", good. ");

代码存在一些问题:

1.while条件始终为真

while (colSel != "Red" || gClas != "Blue" || gClas != "Green")

||运算符(OR 运算符(的工作方式是计算每个表达式,并在其中一个表达式计算结果为true时立即返回true。由于colSel不能超过一个颜色字符串,因此条件将返回true并且while循环将继续。

您要查找的运算符是&&运算符(AND 运算符(,仅当所有表达式都返回true时,它才返回true,否则返回false

2.您正在调用输入ToLower并将其与带有大写字符的字符串进行比较
因此,再一次,没有一个字符串与您的比较相匹配。使用小写字符串是处理此问题的一种方法。

3. 循环内有一个break语句
这意味着"立即退出循环"。它的对应物是continue,这意味着"停止执行当前迭代并再次启动循环"。但是您不需要其中任何一个,因为while循环将自动继续,直到条件返回false

因此,要修复代码,您可以执行以下操作:

Console.Write("Select Colour (Red / Blue / Green): ");
string colSel = Console.ReadLine().ToLower();
while (colSel != "red" && colSel != "blue" && colSel != "green")
{
Console.WriteLine("Sorry, I didn't catch that...");
Console.Write("Select Colour (Red / Blue / Green): ");
colSel = Console.ReadLine().ToLower();
}
Console.WriteLine("Alright " + colSel + ", good. ");

此外,通过使用将输入进行比较的有效值的数组(或列表(,可以使代码更易于维护(并改进字符串比较(。这允许您动态显示有效值(使用数组上的string.Join(并动态验证输入(通过使用不区分大小写的比较器检查输入是否values.Contains(。但在这一点上它可能有点先进。

要尝试一下,只需将您想要的任何字符串添加到数组中,并注意提示如何更改,验证如何自动处理新添加:

// Add any valid values to this array
var validValues = new[] {"Red", "Blue", "Green"};
var prompt = $"Select Colour ({string.Join(" / ", validValues)}): ";
Console.Write(prompt);
string userInput = Console.ReadLine();
while (!validValues.Contains(userInput, StringComparer.OrdinalIgnoreCase))
{
Console.WriteLine($"Sorry, '{userInput}' is not a valid value.");
Console.Write(prompt);
userInput = Console.ReadLine();
}
Console.WriteLine("Alright " + userInput + ", good. ");

循环只运行一次(假设用户不断输入错误的输入(的原因是它在循环结束时包含breakbreak是一个特殊的关键字,用于退出开关情况和循环。

最重要的是,colSel设置了用户输入的小写版本,但 while 循环比较在字符串中使用大写,这意味着正确的用户输入将失败。

尝试:

Console.WriteLine("Select Colour (Red / Blue / Green): ");
string colSel = Console.ReadLine().ToLower();
// strings are now 'lowered'.
// also changed it so that all the variables look to colSel instead
while (colSel != "red" && colSel != "blue" && colSel != "green")
{
Console.WriteLine("Sorry, I didn't catch that...");
Console.Write("Select Colour (Red / Blue / Green): ");
colSel = Console.ReadLine().ToLower();
}
// Use string interpolation instead of concatenation
Console.WriteLine($"Alright {colSel}, good. ");

最新更新