Reputation: 443
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.
Upvotes: 1
Views: 2185
Reputation: 331
As you said, the issue is with recursion.
I'm assuming that playerName
is being declared outside of this method.
What's happening is that playerName
is getting properly assigned on your second call.
Since the variable is at a class level, the value is preserved and printed on your outermost call as well.
Since that call went through the if (inputName.Length < 2)
branch of your condition, thus not reassigning the value of playerName
.
Upvotes: 2
Reputation: 8194
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:
void Main()
{
PlayerInfo();
}
static void PlayerInfo()
{
string inputName = string.Empty;
// This will loop until inputName is longer than 2 characters
while (inputName.Length < 2)
{
Console.Write("Type your name: ");
inputName = Console.ReadLine();
}
// Now that inputName is longer than 2 characters it prints the result only once
Console.WriteLine("Hello " + inputName + "!");
}
Example:
Type your name: A
Type your name: B
Type your name: John
Hello John!
Upvotes: 4