Reputation: 113
I need a method that will ensure that i'm entering correct types of values AND that will get me to the point where i am supposed to enter them again. I do not need recursion to get to the beginning of the method, I need something to get to the place where I'm entering values. I know I am supposed to use loops, but I do not know how to do that. This is part of the method:
console.writeline("Enter your value");
double kv = 0;
try
{
kv = Convert.ToDouble(Console.ReadLine());
}
catch (FormatException)
{
Console.WriteLine("Enter a number");
}
Upvotes: 3
Views: 2218
Reputation: 3752
You can se a do while
loop too:
double kv = 0;
bool invalid = false;
do
{
console.writeline("Enter your value");
try
{
kv = Convert.ToDouble(Console.ReadLine());
invalid = false;
}
catch (FormatException)
{ invalid = true;}
} while (invalid);
Upvotes: 0
Reputation: 6230
Use Double.TryParse
instead of try/catch:
Console.Writeline("Enter your value");
double kv;
while (!Double.TryParse(Console.ReadLine(), out kv))
Console.WriteLine("Enter a number");
Upvotes: 6
Reputation: 31206
Use TryParse
double kv = 0;
Console.WriteLine("Enter your value");
while (double.TryParse(Console.ReadLine(), out kv) == false)
{
Console.WriteLine("Enter your value");
}
Upvotes: 2
Reputation: 203838
You can follow this particular pattern:
var data = GetValueFromUser();
while(!IsValid(data))
{
InformUserTheirDataIsBad();
data = GetValueFromUser();
}
//data is now valid
Upvotes: 6