0

I have a simple console App that converts pounds to kilograms and vice-versa. What I'm attempting to do is if the user enters lb then run the function to convert pounds to kilograms, else if the user enters kg, then run the function to convert kilograms to pounds.

During the setup part of the condition in main, I get an error "Use of unassigned local variable 'lb'

...The Code (snippets):

//method to convert KG to Lbs

public void ConvertKg()
{
    Console.WriteLine("C# KG to LB program\n");

    Console.Write("Enter a number in KG: ");
    double kilograms = Convert.ToDouble(Console.ReadLine());

    double pounds = kilograms * 2.20462262185;
    Console.WriteLine(kilograms + " kilograms is " + pounds + " pounds");


}

//method to convert Lbs to KG

public void ConvertLb()
{
    Console.WriteLine("C# LB to KG program\n");

    Console.Write("Enter a number  in lbs:");
    double pounds_userEntry = Convert.ToDouble(Console.ReadLine());

    double kilogram_userEntry = pounds_userEntry * 0.453592;
    Console.WriteLine(kilogram_userEntry + " kilograms is " + pounds_userEntry + " pounds");


}

...main:

string lb, kg;
string userInput = "";

Console.Write("Enter either lb or kg:");           

if(userInput == lb) // where the error occurs
{
    var k = new ConvertNumber();
    k.ConvertLb();
}
else
{
    var l = new ConvertNumber();
    l.ConvertKg();

}
Console.ReadLine();

...the problem seems to be within the approach I'm using to set up the conditional statement to accept the user's input. ...could I get some help as to what I'm doing wrong?

9
  • What value do you expect the variable lb to have on that line and why? Commented Oct 30, 2019 at 15:08
  • If all the code you have is the one you have posted, then you will get a Null Reference Exception on IF condition since lb is null Commented Oct 30, 2019 at 15:08
  • 1
    @apomene No, comparing to a null variable is fine - but it will generate a compiler error since you have to assign the variable a value before you reference it. Commented Oct 30, 2019 at 15:09
  • 1
    VS will tell you this as it's a warning, read them; lb is unassigned as already mentioned. Commented Oct 30, 2019 at 15:11
  • 1
    What if the user enters asdf (or any other random string) as any of your inputs? Commented Oct 30, 2019 at 15:12

3 Answers 3

2

There is no need to do string lb, kg;, so you can leave it out.

userInput is assigned to "", but it should probably contain something from the user. Replace

string userInput = "";

with

Console.Write("Enter either kg or lb: ");

string userInput = Console.ReadLine() // Console.ReadLine enables the user to type some text and returns it

Because

Console.Write("Enter either kg or lb");

has been done now, you can leave it out afterwards.

Now you can compare userInput with "lb" and "kg".

Replace

if(userInput == lb)
{
    var k = new ConvertNumber();
    k.ConvertLb();
}
else
{
    var l = new ConvertNumber();
    l.ConvertKg();
}
Console.ReadLine();

with

if (userInput == "lb") {
    ConvertLb();
} else if (userInput == "kg") {
    ConvertKg();
} else {
    Console.WriteLine("Your input was neither lb nor kg");
}

Final code (main):

Console.Write("Enter either kg or lb: ");

string userInput = Console.ReadLine() // Console.ReadLine enables the user to type some text and returns it

if (userInput == "lb") { // The user typed "lb"
    ConvertLb();
} else if (userInput == "kg") { // The user typed "kg"
    ConvertKg();
} else { // The user typed neither "lb" nor "kg"
    Console.WriteLine("Your input was neither lb nor kg");
}
Sign up to request clarification or add additional context in comments.

Comments

0

As the comments are mentioning, you have to either initialize the lb variable with "lb" or to compare the userInput directly to the string "lb" as Rakesh is writing in comments. Also I've seen that you don't read the user input.

Below I've created a quick sample code that should do the job that you expect and should be easy to understand.

   class Program
   {
    public const string Lb = "lb"; //User options as constants
    public const string Kg = "kg";

    static void Main(string[] args)
    {
        string userInput = GetUserInput();

        try
        {
            ConvertUserInput(userInput);
        }
        catch (ArgumentException ex)
        {
            Console.WriteLine(ex.Message); // Show error message

            userInput = GetUserInput(); // Get user input again
            ConvertUserInput(userInput);
        }

        Console.ReadLine();
    }

    private static string GetUserInput()
    {
        Console.Write("Enter either lb or kg:");

        string userInput = Console.ReadLine();
        return userInput;
    }

    private static void ConvertUserInput(string userInput)
    {
        // Guard for throwing an error when the user enters another value
        if (!IsValidUserInput(userInput))
            throw new ArgumentException("Input value is not lb or kg");

        if (ConvertFromPoundsToKg(userInput)) // where the error occurs
        {
            var k = new ConvertNumber();
            k.ConvertLb();
        }
        else
        {
            var l = new ConvertNumber();
            l.ConvertKg();
        }
    }

    /// <summary>
    /// userInput is either "lb" or "kg"
    /// </summary>
    /// <param name="userInput"></param>
    /// <returns></returns>
    private static bool IsValidUserInput(string userInput)
    {
        return ConvertFromPoundsToKg(userInput) || (ConvertFromKgToPounds(userInput));
    }

    private static bool ConvertFromKgToPounds(string userInput)
    {
        return userInput == Kg;
    }

    private static bool ConvertFromPoundsToKg(string userInput)
    {
        return userInput == Lb;
    }
}

1 Comment

Thank you, I figured it out, but still your sample in comparison to the additions / modifications I applied helped. ...Thanks again!
0

The problem is that the variable lb is not initialized. It doesn't have a value that you could compare against. I've changed your code to solve this problem. Next steps would be to get the "number" the user entered before the unit and pass it to a unit coversion function and output it to the user again. This will be left for you to do ;)

class Program
{
    static void Main(string[] args)
    {
        //string lb, kg;
        //string userInput = "";

        Console.Write("Enter either lb or kg:");
        string input = Console.ReadLine();
        string unit = input.Substring(input.Length-2);

        if (unit == "lb") // where the error occurs
        {
            int k = ConvertNumber();
            Console.WriteLine(k + "kg");
            //k.ConvertLb();
        }
        else if (unit == "kg")
        {
            int l = ConvertNumber();
            Console.WriteLine(l + "lb");
            //l.ConvertKg();

        }
        else
        {
            Console.WriteLine("invalid unit");
        }
        Console.ReadLine();
    }

    static int ConvertNumber()
    {
        Console.WriteLine("convert");
        return 123;
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.