Home > Back-end >  Beginner Question - While loop for simple password program only looping question
Beginner Question - While loop for simple password program only looping question

Time:11-28

I'm following a tutorial to create a simple command prompt program to ask for password (console.writeline) and write that the password is authenticated if inputted correctly (console.readline if statement) - this runs smoothly:

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");

The next part of the exercise is to ask for the password to be typed again if it is incorrect. I followed the exercise per the tutorial but upon running the program the program loops the question line after line rather than methodically going through the steps of the code.

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");

Would be grateful for any advice! thanks!

CodePudding user response:

Your while loop is missing curly blocks {}. when not specifing {} you the while loop only specifies to the next line instead of code block you wanted.

Also, you don't need the else if (password != "secret"). else is enough

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");
}
  • Related