简单验证

时间:2018-09-06 08:30:22

标签: c# validation console-application

嘿,我的C#控制台程序正在寻找简单的验证码

当前拥有:

public Class1()
{
    Console.WriteLine("Enter a, b, c or d:");
    string input = Console.ReadLine();

    while ((input != "a") && "b" && "c" && "d"))
    {
        if (input == "a" && "b" && "c" && "d")
        {
            Console.WriteLine("Success");
        }

        if (input != "a" && "b" && "c" && "d")
        {
            Console.WriteLine("Try again");

            Console.WriteLine("Enter a, b, c or d:");
            string input = Console.ReadLine();
        }
    }

}

感谢您的帮助!干杯。

8 个答案:

答案 0 :(得分:1)

这是胡说八道:

while ((input != "a") && "b" && "c" && "d"))

可以这样写:

while (aCondition && anotherCondition && yetAnotherCondition && theLastCondition))

(input != "a")是一个条件,没有问题,但是"b"不是条件,因为它不是true或{ {1}}。我想您会写:false

应该将条件null写入while ((input != "a") && (input != "b") && (input != "c") && (input != "d")))的相同方式将引起算法问题。 if (input == "a" && "b" && "c" && "d")不能同时等于if (input == "a" && input == "b" && input == "c" && input == "d"),等于input,等于"a"和等于"b"

此外,由于您的代码位于一个类中,因此没有被包装到方法中,因此无法编译。

尝试运行该消息时,您是否阅读了错误消息?

答案 1 :(得分:1)

我认为最简单的方法是创建允许使用的字符数组,并根据该值验证输入:

char[] allowedChars = new char[] { 'a', 'b'};   

while(true){

    char inputChar = 'z';

    if (allowedChars.Length > 1)
    {
        Console.WriteLine(string.Format("Enter {0} or {1}:", string.Join(", ", allowedChars.Take(allowedChars.Length - 1)), allowedChars[allowedChars.Length - 1]));
    }
    else
    {
        Console.WriteLine(string.Format("Enter {0}", allowedChars[0]));
    }

    var result = char.TryParse(Console.ReadLine(), out inputChar);

    if (result && allowedChars.Contains(inputChar))
    {
        break;
    }

    Console.WriteLine("Try again");
}

Console.WriteLine("Success");
Console.ReadLine();

成功后,它将自动从while循环中跳出并显示成功消息。

答案 2 :(得分:0)

首先,您的代码不能仅在类中。它必须在一个函数中。通常,您会看到这样的样子

    Console.WriteLine("Enter a, b, c or d:");
    while ((input != "a") &&(input != "b") && (input != "c") &&(input != "d"))
    {
        Console.WriteLine("Try again");
        string input = Console.ReadLine();
    }
    Console.WriteLine("Success!");

答案 3 :(得分:0)

我建议使用以下代码:

// char: we actually input a single character, not string
char input = '\0'; // initialize to make compiler happy

// keep on asking until success
while (true) {
  Console.WriteLine("Enter a, b, c or d:"); 

  // ReadKey: We want a single character, not a string
  input = Console.ReadKey();   

  // input is valid if it's in ['a'..'d'] range
  if (input >= 'a' && input <= 'd') {
    Console.WriteLine("Success");

    break;
  }

  Console.WriteLine("Try again"); 
}

编辑:在一般情况下(请参见下面的Adriani6的注释),代码要复杂一些。我猜潜在的问题是一种 questionary ,例如

Compute 2 x 2 = ?
  a. 3
  b. 4
  c. 5
  d. 0  

Enter a, b, c or d:

这就是为什么我希望有效的input应该在我保存的范围(在上面的示例中为'a'..'d')范围内。

char from = 'a';
char upto = 'd';

// char: we actually input a single character, not string
char input = '\0'; // initialize to make compiler happy

// Building a title is, probably, the only complex thing (Linq)
string title = 
  $"Enter {string.Join(", ", Enumerable.Range(from, upto - from).Select(c => (char) c))} or {upto}:";

// keep on asking until success
while (true) {
  Console.WriteLine(title); 

  // ReadKey: We want a single character, not a string
  input = Console.ReadKey();   

  // Uncomment if we want a quit without choice, say, on Escape 
  //if (input == 27) { // or (input == 'q') if we want to quit on q
  //  input = '\0';
  //
  //  break;
  //}  

  // input is valid if it's in [from..upto] range
  if (input >= from && input <= upto) {
    Console.WriteLine("Success");

    break;
  }

  Console.WriteLine("Try again"); 
}

答案 4 :(得分:0)

您的代码中有很多错误,请看一下我的并尝试理解它。很简单。

 Console.WriteLine("Enter a, b, c or d:\r\n");
   string input = Console.ReadLine();
   while (input != "")
   {
     if (input == "a" || input == "b" || input == "c" || input == "d")
      {
       Console.WriteLine("Success\r\n");
      }
     else
      {
       Console.WriteLine("Fail\r\n");
      }
     Console.WriteLine("Enter a, b, c or d:");
     input = Console.ReadLine();
    }

答案 5 :(得分:0)

 public Class1()
{

    private static List<string> allowedChars= new List<string>(){
         "a","b","c","d"
     };
     public void Verify()
     {
          Console.WriteLine("Enter a, b, c or d:");
          string input = Console.ReadLine();
          while (!allowedChars.Contains(input))
         {
              Console.WriteLine("Try again");       
              Console.WriteLine("Enter a, b, c or d:");
              input = Console.ReadLine();
          }
    }
}

答案 6 :(得分:0)

为什么要使用while循环?似乎是不必要的。对于正确答案,我不了解您的代码,但是简单的switch语句应该可以更好地满足您的目的

        Console.WriteLine("Enter a, b, c or d:");
        string input = Console.ReadLine();

        switch (input)
        {
            case "a": Console.WriteLine("Success");
                break;
            case "b":
                Console.WriteLine("Try again");
                break;
            case "c":
                Console.WriteLine("Try again");
                break;
            case "d":
                Console.WriteLine("Try again");
                break;
            default: Console.WriteLine("Enter a, b, c or d:");
                break;
        }

        Console.ReadLine();

答案 7 :(得分:0)

对于初学者来说,我会将验证码输入分解为一个单独的方法,因为如果输入验证失败,您可能必须多次调用它。检索输入也是如此。

对于验证本身,将简单检查输入字符串与“ a”或“ b”或“ c”或“ d”匹配。您可以设置该方法以返回表达式求值的布尔值,如下所示。

最后,这只是调用ValidateInput直到使用While循环返回true并使用逻辑否定运算符!否定返回值的情况。否定返回值有效地反转了ValidateInput方法的结果。在英语中,这将显示为While ValidateInput is NOT True

class Program
{
    static void Main(string[] args)
    {
        while (!ValidateInput(GetInput()))
        {
            Console.WriteLine("Try again");
        }

        Console.WriteLine("Success");
        Console.Read();
    }

    private static string GetInput()
    {
        Console.WriteLine("Enter a, b, c or d:");
        return Console.ReadLine();
    }

    private static bool ValidateInput(string input)
    {
        return (input == "a" || input == "b" || input == "c" || input == "d");
    }
}