How to implement a method that calls itself?

I got a wrist because in the assignment I had a method call when an input error was made. I don’t know how and what to use instead of the code I wrote. I need help finding the right way to do this.

I like the code, so I just need to push the right way! :)

The code written by me 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; } } 
+4
source share
3 answers

The standard way to implement this would be with a while loop.

 int num; while (!int.TryParse(Console.ReadLine(), out num)) { Console.WriteLine("Your input is not valid, please try again.\n"); } 
+7
source

Personally, I kind of like this style, but it is inefficient (and can potentially lead to a stack overflow if the user has entered invalid input a huge number of times). Your teacher probably wanted you to use the while :

 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, this false == bit is very non-idiomatic and will raise eyebrows on most commands (as a note: if your instructor advised you to write this, it probably comes from a different language background where this is a guarantee against accidental assignment, believe me, this is not necessary or normal on land C #). This looks a lot more typical:

 while (!int.TryParse(Console.ReadLine(), out num)) { // etc. } 
+8
source

Use a while loop.

 Console.Write("Please give the value no "+ index + " :"); while(!int.TryParse(Console.ReadLine(), out num)) //I find "!" easier to read then "false == " { Console.WriteLine("Your input is not valid, please try again."); Console.WriteLine(); Console.Write("Please give the value no "+ index + " :"); } 

There is no need for recursion, so it’s better to do a while loop.

+1
source

All Articles