Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bool statement in a while loop c#

Tags:

c#

boolean

For this code, I had a goto start; statement to repeat the section until a valid name was entered, however my teacher does not like the goto so I had to change it.

Currently this is what i got but I'm not sure why is it not working. To begin with the program wont even start cuz later in the code I use the input userName and it does not recognize it when I use it in the bool statement. For the purpose of testing it I removed the userName line later on and the program opens but skips the bool statement.

Please help me make this work. thanks

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;
    }
}
like image 847
Brian Naranjo Avatar asked Dec 03 '25 15:12

Brian Naranjo


1 Answers

Set the 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;
  }
}
like image 153
Abdur Rahim Avatar answered Dec 06 '25 15:12

Abdur Rahim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!