简单的验证

问题描述 投票:0回答:8

嘿伙计们为我的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();
        }
    }

}

任何帮助表示赞赏!干杯。

c# validation console-application
8个回答
1
投票

这是胡说八道:

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

它可以这样写:

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

(input != "a")是一个条件,没有问题,但"b"不是一个条件,它将被视为true,因为它不是falsenull。我想你会写: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",等于"c",等于"d"

此外,您的代码将无法编译,因为它在一个类中而不包含在方法中。

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


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循环中突破并打印Success消息。


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!");

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

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

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

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的评论)代码有点复杂。我想潜在的问题是一种质疑,比如

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"); 
}

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");
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.