0

I'm trying to validate if the 'columnsValidation' is a numeric string, and convert it to an int, if so.

For some reason, I end up in an endless loop, because 'isNumber' always equals false...

This code is part of my lottery project.

I hope that my question is clear enough, if additional information is needed just tell me and I'll answer.

Thanks in advance, Ilan.

Console.WriteLine("Please insert the number of rows: ");

        string columnsValidation = Console.ReadLine();

        bool isNumber = false;

            while(isNumber == false)
            {
                bool.TryParse(columnsValidation, out isNumber);
                if (isNumber == true)
                    columns = int.Parse(columnsValidation);
                else
                {
                    Console.WriteLine("You've inserted an invalid value, please try again.");
                    columnsValidation = Console.ReadLine();
                }
            }
3
  • Your code looking for true as input... Commented Jan 21, 2014 at 18:30
  • bool.TryParse tries to get a bool out of 'true' or 'false' and tells you nothing about if columsValidaton is a number. Commented Jan 21, 2014 at 18:30
  • The way you are using bool.TryParse is incorrect. If you aren't going to use it's output, then you might as well use bool.Parse(columnsValidation) Commented Jan 21, 2014 at 18:30

3 Answers 3

2

You need to use int.TryParse with columnsValidation

if (!int.TryParse(columnsValidation,out columns)
{
     Console.WriteLine("You've inserted an invalid value, please try again.");
     columnsValidation = Console.ReadLine();
}
else
{ 
    isNumber = true;
}
Sign up to request clarification or add additional context in comments.

Comments

2

Correct your usage of TryParse:

isNumber = int.TryParse(columnsValidation, out columns);

TryParse returns boolean indicating whether the parsing succeeded, and in case of success sets out param with the parsing result.

Comments

0

Why not you use Int.TryParse

int columns = 0;

while(true)
{
    if (!Int32.TryParse(columnsValidation,out columns)
    {
        Console.WriteLine("You've inserted an invalid value, please try again.");
        columnsValidation = Console.ReadLine();
    }
    else
    {
        break;
    }
}

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.