对于这段代码,我有一个开始;语句重复该部分,直到输入有效名称,但是我的老师不喜欢 goto,所以我不得不更改它。
目前这是我得到的,但我不确定为什么它不起作用。开始时程序甚至不会启动,因为稍后在代码中我使用输入用户名,当我在 bool 语句中使用它时它无法识别它。为了测试它,我稍后删除了 userName 行,程序打开但跳过 bool 语句。
请帮助我完成这项工作。谢谢
bool nameValidation = true;
while (nameValidation == false) {
Console.Write("Enter your name: "); // Asks for your name
userName = Console.ReadLine();
if (Regex.IsMatch(userName, @"^[a-zA-Z- ]+$")) // Validates the input containts characters and/or spaces
{
nameValidation = true;
}
else // Error message if the input is not valid
{
Console.Clear(); // Clear screen
Console.WriteLine("Please enter a valid name.");
nameValidation = false;
}
}
最佳答案
设置nameavalidation = false
bool nameValidation = false;
while (nameValidation == false) {
Console.Write("Enter your name: "); // Asks for your name
userName = Console.ReadLine();
if (Regex.IsMatch(userName, @"^[a-zA-Z- ]+$")) // Validates the input containts characters and/or spaces
{
nameValidation = true;
}
else // Error message if the input is not valid
{
Console.Clear(); // Clear screen
Console.WriteLine("Please enter a valid name.");
nameValidation = false;
}
}
关于c# - while循环中的bool语句c#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35262972/