Kyle Myott Kyle Myott - 1 month ago 15
C# Question

C# Console Application Password Input Checker

The following code has preset passwords that the user must enter to continue the code. However, when the set passwords (PASS1-PASS3) are entered, the code goes to the do-while regardless. What do I need to do in order to make the while recognize that the password is correct so that it does not go to the invalid password line?

// Program asks user to enter password
// If password is not "home", "lady" or "mouse"
// the user must re-enter the password
using System;
public class DebugFour1
{
public static void Main(String[] args)
{
const String PASS1 = "home";
const String PASS2 = "lady";
const String PASS3 = "mouse";
String password;
String Password;
Console.Write("Please enter your password ");
password = Console.ReadLine();
do
{
Console.WriteLine("Invalid password enter again: ");
password = Console.ReadLine();
} while (password != PASS1 || password != PASS2 || password != PASS3);
Console.WriteLine("Valid password");
Console.ReadKey();

}
}

Answer

You have your logic the wrong way around i.e. do something then check some conditions, whereas you want to check some conditions and then do something. So the following code:

do
{
    Console.WriteLine("Invalid password enter again: ");
    password = Console.ReadLine();
} while (password != PASS1 || password != PASS2 || password != PASS3);

Should read:

while (password != PASS1 && password != PASS2 && password != PASS3)
{
    Console.WriteLine("Invalid password enter again: ");
    password = Console.ReadLine();
} 

Notice that I also changed the logical ORs || to logical ANDs &&. this is because you want to check if it is not equal to all of them, not just one.

On a side note the variable Password is unused and should be removed as it can lead to typo errors to your used variable password.

Comments