Home > front end >  Unwanted repeat in method (with user input)
Unwanted repeat in method (with user input)

Time:10-23

I have a fairly specific question on this otherwise functional piece of code. The problem is that whenever I run it, there is always a blank spot after the value, so the user has to enter their input twice. So the output would say... pic related

    public string GetPayType()
    {
        Console.WriteLine("Please enter 1 if your pay type is a weekly hourly wage and 2 if your pay type is a monthly salary:");
        if (Console.ReadLine() == "1")
        {
            payType = Convert.ToString(Console.ReadLine());
            return payType;
        }
        else if (Console.ReadLine() == "2") 
        {
            payType = Convert.ToString(Console.ReadLine());
            return payType;
        }
        else
        {
            Console.WriteLine("Error! You may only enter a 1 or a 2!");
        }
        return payType;
    }

CodePudding user response:

By doing the line below again after comparing the first input, you are basically prompting for another input to return.

payType = Convert.ToString(Console.ReadLine());
return payType;

Try:

public string GetPayType()
    {
        Console.WriteLine("Please enter 1 if your pay type is a weekly hourly wage and 2 if your pay type is a monthly salary:");
        payType = Console.Readline();
        if (payType == "1" || payType == "2")
        {
            return payType;
        }
        else
        {
            Console.WriteLine("Error! You may only enter a 1 or a 2!");
        }
        return null;
    }

You might as well want to add a loop for the user if they entered an invalid input, I'll leave that to you for your own research.

  • Related