Reputation: 15
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();
}
}
Upvotes: 0
Views: 211
Reputation: 3781
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;
}
}
Upvotes: 0
Reputation: 101681
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;
}
Upvotes: 2
Reputation: 56688
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.
Upvotes: 2