Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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");
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading