Search code examples
c#recursionconsole.writeline

Console.WriteLine repeating itself for some reason


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.


Solution

  • 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!

    See it working on .NET Fiddle