2

I have designed an input validation loop in C#, and I would like it to be able to check for the correct input format. I'm not sure, but I think my designed loop is not checking the type of input, just what char is entered. I know I could use a try-catch block, but shouldn't you only use exceptions for exceptional situations? This is not an exceptional situation, because I expect that the user would enter an incorrect value.

Question:

Is there a way I could redesign this loop so that it checks for valid input type as well?

Code:

do
{
    Console.Write("Do you wish to enter another complex number?: (Y or N)");
    response = char.Parse(Console.ReadLine());
    response = char.ToUpper(response);

    if (response != 'Y' && response != 'N')
        Console.WriteLine("You must respond Y or N!");

} while (response != 'Y' && response != 'N');
2
  • What do you mean by "input type"? You are accepting a lower/uppercase Y or N and rejecting everything else - what more are you thinking you need to do? Commented Dec 5, 2009 at 22:48
  • Why the random downvote, this is a valid question with his proposed solution and he is asking for advice. Don't downvote with no explanation people. Commented Mar 26, 2010 at 13:25

3 Answers 3

2

Well Console.Readline():

Reads the next line of characters from the standard input stream.

So your data will be of type System.String.

The only other checking you could do is to check that the returned string is of length 1, so you know you have input of the right format. You don't really need the char.Parse as the elements of a string are of type char.

Sign up to request clarification or add additional context in comments.

1 Comment

thank you! I didn't think about checking the length of the string!
1

I don't know what your original asigment is, but the example you provided can be simplyfied by just comparing strings, ie:

response = Console.ReadLine(); 
if (response.ToUpper() == "Y") {...}

If you want to see if the input can be cast to the type you need (for example char), you can allways do (for every value type):

char input;
bool IsValid = char.TryParse(Console.ReadLine().ToUpper(), out input);
if (IsValid) 
{
    Console.WriteLine("You entered the following char: " + input);
}

Hope this helps.

Comments

0

Another helpful check in such a situation

Checks for a null string , "" (Empty string) and trims extra white space I.E s string like this " " become this ""

if(String.IsNullOrEmpty(response.Trim() && response != 'Y' && response != 'N'))
{ Console.WriteLine("You must respond Y or N!"); }

And for the most part it is easier to use strings over char in most simple input validation situations.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.