Reputation: 13
I am a complete beginner to c# and I am trying to create a very simple login program. I have the following code:
do
{
AdvancedUtilities.TyperwriterTextEffect("Please create a password for your account (8-10 characters): ");
AccountPassword = Console.ReadLine();
_accountPassword = AccountPassword;
} while (_accountPassword.Length < 8 && _accountPassword.Length >= 10);
However, every time the input doesn't meet the while loop conditions, the same message will show again
"Please create a password for your account (8-10 characters)"
How can i make it so that i show an error message like
"Please try again: "
instead of repeating the original one?
Upvotes: 0
Views: 548
Reputation: 52280
You need two messages.
AdvancedUtilities.TyperwriterTextEffect("Please create a password for your account (8-10 characters): ");
while (true)
{
AccountPassword = Console.ReadLine();
_accountPassword = AccountPassword;
if (_accountPassword.Length >= 8 && _accountPassword.Length < 10) break;
AdvancedUtilities.TyperwriterTextEffect("Please try again: ");
}
Note: There are ways to write this without using while(true)
but to me this is the clearest way that avoids code duplication. When you use while(true)
it signals to anyone reading your code to look for the break
and continue
flow of control keywords.
Upvotes: 0
Reputation: 933
Simply put the message in a variable and change the variable after you show it the first time.
The length cannot be simultaneously less than 8 AND greater than 10 characters in length so I only used your condition that made sense.
string message = "Please create a password for your account (8-10 characters): ";
do
{
AdvancedUtilities.TyperwriterTextEffect(message);
AccountPassword = Console.ReadLine();
_accountPassword = AccountPassword;
message = "Please try again";
} while (_accountPassword.Length < 8);
Upvotes: 2