初学者问题 - While loop for simple password program only looping question

Beginner Question - While loop for simple password program only looping question

我正在按照教程创建一个简单的命令提示符程序来询问密码 (console.writeline) 并写明如果输入正确则密码已通过身份验证 (console.readline + if 语句) -这运行顺利:

Console.WriteLine("Please Input Your Password:");
var password = Console.ReadLine();
if (password == "secret")
Console.WriteLine("You have been authenticated");
else if (password != "secret")
Console.WriteLine("You have not been authenticated");

练习的下一部分是要求在密码不正确时重新输入密码。我按照教程进行了练习,但是在 运行 程序中,程序逐行循环问题,而不是有条不紊地执行代码步骤。

var password = "";
while (password !="secret")
Console.WriteLine("Please Input Your Password:");
password = Console.ReadLine();
if (password == "secret")
Console.WriteLine("You have been authenticated");
else if (password != "secret")
Console.WriteLine("You have not been authenticated");

如有任何建议,我们将不胜感激!谢谢!

您的 while 循环缺少卷曲块 {}。当你没有指定 {} 时,while 循环只指定到下一行而不是你想要的代码块。

此外,您不需要 else if (password != "secret")else 够了

var password = "";
while (password !="secret")
{
  Console.WriteLine("Please Input Your Password:");
  password = Console.ReadLine();
  if (password == "secret")
     Console.WriteLine("You have been authenticated");
  else
     Console.WriteLine("You have not been authenticated");
}