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;
}
}
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.
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With