Kyle Russell
Kyle Russell

Reputation: 69

Simple validation

Hey guys looking for a simple validation code for my C# Console Program

Currently have:

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

}

Any help is appreciated! Cheers.

Upvotes: 0

Views: 183

Answers (8)

T_Bacon
T_Bacon

Reputation: 414

For starters, I would break out the validation code input into a separate method as you're potentially going to have to call it multiple times if the input validation fails. The same applies for retrieving the input.

As for the validation itself, a simple check that the input string matches "a" OR "b" OR "c" OR "d" will work. You can set up the method to return the boolean value that the expression evaluates to, as below.

Finally, it's just a case of calling ValidateInput until it returns true using a While loop and negating the returned value using the logical negation operator !. Negating the returned value effectively reverses the result of the ValidateInput method. In English this would read as 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");
    }
}

Upvotes: 0

Adrian
Adrian

Reputation: 8607

I think the simplest approach would be to create an array of chars that are allowed and validate the input against that:

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

When it's a success it'll automatically break out from the while loop and print the Success message.

Upvotes: 1

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186843

I suggest the following code:

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

Edit: in generalized case (see Adriani6's comment below) the code be a little bit more complex. I guess the underlying problem being a kind of questionary, like

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

Enter a, b, c or d:

that's why I expect the valid input should ever be in some range ('a'..'d' in the example above) which I preserved.

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

Upvotes: 0

Cid
Cid

Reputation: 15257

This is a nonsense :

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

It can be written that way :

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

(input != "a") is a condition, there's no problem with that, but "b" isn't a condition, it will be considered as true since it's not false or null. I think you would have write : while ((input != "a") && (input != "b") && (input != "c") && (input != "d")))

The same way that condition if (input == "a" && "b" && "c" && "d") should have be written if (input == "a" && input == "b" && input == "c" && input == "d") will provide an algo issue. input can't be at the same time equal to "a", equal to "b", equal to "c" and equal to "d".

Plus, your code won't compile since it's in a class without being wrapped into a method.

Did you read the errors message when trying to run it?

Upvotes: 1

bzLoLIp0p
bzLoLIp0p

Reputation: 91

Why do you use a while loop? It seems quite unneccessary. I do not understand your code as to what the right answer would be, but a simple switch statement should serve your purpose better

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

Upvotes: 0

Guy haimovitz
Guy haimovitz

Reputation: 1625

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

Upvotes: 0

Cesar
Cesar

Reputation: 527

There is a lot of mistakes in your code, look at mine and try to understand it. It's pretty easy.

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

Upvotes: 0

Prodigle
Prodigle

Reputation: 1797

Firstly, your code cannot just be in a class. It needs to be in a function. Generally you'll see that looking like this

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

Upvotes: 0

Related Questions