I'm an absolute beginner in C# and have written this code, and the output is making me confused:
static void PlayerInfo() //Asking information about the player
{
Console.Write("Type your name: ");
string inputName = Console.ReadLine();
if (inputName.Length < 2)
PlayerInfo();
else
playerName = inputName;
Console.WriteLine("Hello " + playerName + "!");
}
If I type J first, it will ask me again till I type at least 2 characters. And if I type John Doe afterwards, it will give me this output twice Console.WriteLine("Hello " + playerName + "!");
I don't understand why, It looks like this in the console:
Type your name: J //The length is smaller than 2
Type your name: John Doe //Restart the function and type a valid length
Hello John Doe! //This is OK
Hello John Doe! //Why a second print?
It's probably not the best practice to use a recursive method. I'm doing it just to learn the language.
The issue occurs because of the recursion.
You call
PlayerInfo()
two times so you get the output twice, it's as simple as that.If you'd typed "A", then "B", then "John" you'd get the output 3 times and so on.
The answer is to take out the recursion. If you wish to keep prompting until you receive a valid input then one solution is a
while
loop:Example:
See it working on .NET Fiddle