Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement Method that calls itself?

I got my wrist slapped because in an assignment i had a method call itself when an input error was made. I have no idea how to or what to use instead of the code i wrote. I need help to find the correct way on how to do it.

I love to code so i just need a nudge in the right way! :)

The code i had written looks like this.

 private void SumTheNumbers()
 {
 Console.Write("Please give the value no "+ index + " :");
        if (false == int.TryParse(Console.ReadLine(), out num))
        { 
            //Errormessage if the user did not input an integer.
            Console.WriteLine("Your input is not valid, please try again.");
            Console.WriteLine();
            sum = 0;
            SumTheNumbers();
        }
        else
        {
            //Calculate the numbers given by user
            sum += num;
        }
  }
like image 331
user1501127 Avatar asked Dec 04 '22 15:12

user1501127


1 Answers

Personally I kind of like that style, but it is inefficient (and could potentially result in a stack overflow, if the user entered invalid input a huge number of times). Your instructor probably wanted you to use a while loop:

Console.Write("Please give the value no "+ index + " :");
while (false == int.TryParse(Console.ReadLine(), out num))
{ 
    //Errormessage if the user did not input an integer.
    Console.WriteLine("Your input is not valid, please try again.");
    Console.WriteLine();
    sum = 0;
}

//Calculate the numbers given by user
sum += num;

By the way, that false == bit is very non-idiomatic, and would raise eyebrows on most teams (as a side note: if your instructor advised you to write that, he/she probably comes from a different language background where it's a safeguard against accidental assignment; trust me, it's not necessary or normal in C# land). This looks a lot more typical:

while (!int.TryParse(Console.ReadLine(), out num))
{
    // etc.
}
like image 65
Dan Tao Avatar answered Dec 10 '22 09:12

Dan Tao