user2517370
user2517370

Reputation: 113

Loop in try catch block

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

Answers (4)

unlimit
unlimit

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

Zong
Zong

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

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

Servy
Servy

Reputation: 203838

You can follow this particular pattern:

var data = GetValueFromUser();
while(!IsValid(data))
{
    InformUserTheirDataIsBad();
    data = GetValueFromUser();
}
//data is now valid

Upvotes: 6

Related Questions