我是c#的完全初学者,我正在尝试创建一个非常简单的登录程序。我有以下代码:
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);
但是,每次输入不满足while循环条件时,相同的消息将再次显示
“请为您的帐户创建密码(8-10个字符)”
如何才能使其显示错误信息,如
“请重试:”
而不是重复原来的那个?
发布于 2021-10-26 22:32:08
你需要两条信息。
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: ");
}
注意:有一些方法可以在不使用while(true)
的情况下编写代码,但对我来说,这是避免代码重复的最清晰的方法。当您使用while(true)
时,它会向阅读您的代码的任何人发出信号,以查找控制关键字的break
和continue
流。
发布于 2021-10-26 22:31:27
只需将消息放入变量中,并在第一次显示变量后更改它。
长度不能同时小于8和大于10个字符的长度,所以我只使用您的条件,这是有意义的。
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);
https://stackoverflow.com/questions/69730580
复制相似问题