C#控制台应用程序密码输入检查器

时间:2016-11-01 13:50:06

标签: c# console-application password-checker

以下代码具有用户必须输入以继续代码的预设密码。但是,当输入设置密码(PASS1-PASS3)时,代码无论如何都会进入do-while。我需要做些什么才能让密码正确无法识别密码是否正确无效?

// 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();

 }
}

2 个答案:

答案 0 :(得分:0)

尝试更改" ||"到"&&"。

它不会立刻与所有人相等。

答案 1 :(得分:0)

你的逻辑错误,即做一些事情,然后检查一些条件,而你想检查一些条件,然后做一些事情。所以下面的代码:

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

应阅读:

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

请注意,我还将逻辑OR ||更改为逻辑AND &&。这是因为你想检查它是否不等于所有这些,而不只是一个。

注意,变量Password未使用,应删除,因为它可能会导致使用变量password出现拼写错误。