【问题标题】:C# Console Application Password Input CheckerC# 控制台应用程序密码输入检查器
【发布时间】:2017-03-14 16:07:35
【问题描述】:

以下代码具有预设密码,用户必须输入才能继续代码。但是,当输入设置的密码 (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();

 }
}

【问题讨论】:

  • 用逻辑 AND && 替换您的 While 循环。 while (password != PASS1 && password != PASS2 && password != PASS3); 这里不需要 do-while 循环。 while 循环有效。

标签: c# console-application password-checker


【解决方案1】:

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

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 出现拼写错误。

【讨论】:

    【解决方案2】:

    尝试更改“||”到“&&”。

    它不能同时等于所有这些。

    【讨论】:

      猜你喜欢
      • 2017-09-10
      • 2011-04-09
      • 1970-01-01
      • 1970-01-01
      • 2011-03-25
      • 1970-01-01
      • 1970-01-01
      • 2018-05-18
      相关资源
      最近更新 更多