C# 控制台应用程序密码输入检查器
C# Console Application Password Input Checker
以下代码已预设密码,用户必须输入这些密码才能继续执行代码。但是,当输入设置的密码 (PASS1-PASS3) 时,代码无论如何都会转到 do-while。我需要做什么才能让 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();
}
}
尝试更改“||”到“&&”。
它不能一次等于所有的。
你的逻辑是错误的,即做某事然后检查一些条件,而你想检查一些条件然后做某事。所以下面的代码:
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
.
出现拼写错误
以下代码已预设密码,用户必须输入这些密码才能继续执行代码。但是,当输入设置的密码 (PASS1-PASS3) 时,代码无论如何都会转到 do-while。我需要做什么才能让 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();
}
}
尝试更改“||”到“&&”。
它不能一次等于所有的。
你的逻辑是错误的,即做某事然后检查一些条件,而你想检查一些条件然后做某事。所以下面的代码:
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
.