【问题标题】:c# console Make sure user typed a password [closed]c#控制台确保用户输入密码[关闭]
【发布时间】:2018-01-16 02:11:30
【问题描述】:

很抱歉,如果问题是愚蠢的,不知道谷歌是什么而一无所获,我有一个 控制台应用程序,它从用户那里获取密码并将其设置在文件中。我想确保用户输入了密码并且不要将其留空(只需按下 Enter 键)。如果他没有输入任何东西 应用程序一次又一次地要求他输入密码直到他输入一些东西

bool isitempty = true;
while (isitempty)
{
    var passwordFile = Console.ReadLine();
    if (passwordFile == "")
    {
        Console.WriteLine("sorry, type again");
    }
    else
    {
        zip.Password = String.Format("{0}", passwordFile);
    }
    isitempty = false;
}

我运行了这个,但它只询问一次,如果用户再次将其留空,它将通过这一步。

【问题讨论】:

  • 尝试将isitempty = false; 语句向上移动到else 块中。
  • 移动 isiteempty = false;在 else 子句中。
  • 哈哈谢谢修复。 @Lasse V.卡尔森

标签: c# while-loop console-application


【解决方案1】:
static void Main(string[] args)
{
    string password = null;

    do
    {
        Console.Write("Password: ");
        password = Console.ReadLine();
    }
    while (string.IsNullOrWhiteSpace(password));

    // do something with the password
}

【讨论】:

  • 我从来没有发现“丑陋”的用途,而这仍然不是其中之一。
  • 仅供参考,我删除了我的赞成票,因为您错过了“哎呀”消息
  • @musefan 我看不出do-while 循环“丑陋”的原因以及为什么你不应该使用它:不同的编码偏好do 允许你实现相同的目标(我的答案中的代码与接受的答案中的代码相同)。
  • @musefan 此外,两个循环都被翻译成几乎相同的 IL,除了 while 循环开头的无条件跳转。
  • 这很丑,因为你必须等到最后才能弄清楚循环的逻辑是什么。无论如何,这是首选。但事实是,您所做的与接受的答案不同。根据 OP 问题,您的哪一部分代码输出 "sorry, type again"
【解决方案2】:

解决问题的最简单的代码更改是将isitempty = false; 语句向上移动到else 块中:

    ....
    else
    {
        zip.Password = String.Format("{0}", passwordFile);
        isitempty = false;
    }
}

“更好”(在我看来)重写是像这样重构代码:

string passwordFile = string.Empty;
while (string.IsNullOrWhiteSpace(passwordFile))
{
    passwordFile = Console.ReadLine();
    if (string.IsNullOrWhiteSpace(passwordFile))
        Console.WriteLine("sorry, type again");
}
zip.Password = passwordFile;

这边:

  • 您没有要跟踪的额外变量,它是您需要跟踪和检查的密码变量
  • 格式为{0}时不需要string.Format,直接使用参数即可(只要是字符串即可)

注意我对您的代码所做的一项更改,我将“必须输入某些内容”解释为“也不允许只输入空格”。如果这是不正确的,并且密码确实只能包含空格,您应该替换两个出现的

string.IsNullOrWhiteSpace(passwordFile)

用这个:

string.IsNullOrEmpty(passwordFile)

注意:如果您的 .NET Framework 版本早于 4.0,则必须使用 string.IsNullOrEmpty,因为 string.IsNullOrWhiteSpace 是在 .NET 4.0 中首次引入的。

【讨论】:

  • 同意,已修复,因此两个语句具有相同的逻辑。
  • 为什么它在“IsNullOrWhiteSpace”上给我错误,说:字符串不包含“IsNullOrWhiteSpace”的定义。
  • 你是复制粘贴还是写IsNullOrWhitespace(注意space中的小写s
  • @AidenStewart 您使用的是什么版本的 .NET?
  • @MattJones 是的,哎呀,这里可能是一个较旧的 .NET 框架版本。
猜你喜欢
  • 2014-01-24
  • 1970-01-01
  • 1970-01-01
  • 2011-08-27
  • 2017-09-10
  • 1970-01-01
  • 1970-01-01
  • 2017-03-14
  • 1970-01-01
相关资源
最近更新 更多