Ninjatix
Ninjatix

Reputation: 75

How to loop an if-statement with many else if conditions

I have an issue looping the if-statement in my code. I looked at other threads on stackoverflow but I couldn't get it to work multiple times. The program I'm trying to create is a basic converter for a casting company. What I tried to do is make it so that the user can input the type of conversion needed then the weight of the wax. It would then give the user the correct amount of grams of precious metal to use. The issue is that I need it to run from the beginning until the user is done using it. I tried using a while statement but it just loops the else part of the if-statement. Here's my code for reference:

static void Main(string[] args)
    {
        double waxWeight, bronzeWeight, silverWeight, fourteenkGoldWeight,
            eighteenkGoldWeight, twentytwokGoldWeight, platinumWeight;
        string wW;

        bool doesUserWantToLeave = false;

        Console.WriteLine("Please specify the type of conversion you would like to accomplish:" 
            + "\n(Bronze, Silver, 14k Gold, 18k Gold, 22k Gold, Platinum, or Exit):");

        string conversionType = Console.ReadLine();

        //bool B = conversionType == "Bronze";
        //bool S = conversionType == "Silver";
        //bool ftG = conversionType == "14k Gold";
        //bool etG = conversionType == "18k Gold";
        //bool ttG = conversionType == "22k Gold";
        //bool P = conversionType == "Platinum";

        while (!doesUserWantToLeave)
        {

            if (conversionType == "Bronze")
            {
                Console.WriteLine("What is the weight of the wax model?");
                wW = Console.ReadLine();
                waxWeight = double.Parse(wW);

                bronzeWeight = waxWeight * 10;
                Console.WriteLine("You need " + bronzeWeight + " grams of bronze.");
                Console.ReadLine();
            }

            else if (conversionType == "Silver")
            {
                Console.WriteLine("What is the weight of the wax model?");
                wW = Console.ReadLine();
                waxWeight = double.Parse(wW);

                silverWeight = waxWeight * 10.5;
                Console.WriteLine("You need " + silverWeight + " grams of silver.");
                Console.ReadLine();
            }

            else if (conversionType == "14k Gold")
            {
                Console.WriteLine("What is the weight of the wax model?");
                wW = Console.ReadLine();
                waxWeight = double.Parse(wW);

                fourteenkGoldWeight = waxWeight * 13.5;
                Console.WriteLine("You need " + fourteenkGoldWeight + " grams of 14 Karat gold.");
                Console.ReadLine();
            }

            else if (conversionType == "18k Gold")
            {
                Console.WriteLine("What is the weight of the wax model?");
                wW = Console.ReadLine();
                waxWeight = double.Parse(wW);

                eighteenkGoldWeight = waxWeight * 15;
                Console.WriteLine("You need " + eighteenkGoldWeight + " grams of 18 Karat gold.");
                Console.ReadLine();
            }

            else if (conversionType == "22k Gold")
            {
                Console.WriteLine("What is the weight of the wax model?");
                wW = Console.ReadLine();
                waxWeight = double.Parse(wW);

                twentytwokGoldWeight = waxWeight * 17.3;
                Console.WriteLine("You need " + twentytwokGoldWeight + " grams of 22 Karat gold.");
                Console.ReadLine();
            }

            else if (conversionType == "Platinum")
            {
                Console.WriteLine("What is the weight of the wax model?");
                wW = Console.ReadLine();
                waxWeight = double.Parse(wW);

                platinumWeight = waxWeight * 21.5;
                Console.WriteLine("You need " + platinumWeight + " grams of platinum.");
                Console.ReadLine();
            }

            else if (conversionType == "Exit")
            {
                doesUserWantToLeave = true;
            }

            else
            {
                Console.WriteLine("Sorry! That was an invalid option!");
                Console.ReadLine();
            }
        }
    }

I realize that a good programmer doesn't type the same code twice but I'm just not at that level yet, I just want the code to loop. Would I have to make it a big nested if-statement?

Upvotes: 6

Views: 266

Answers (3)

Melvin
Melvin

Reputation: 324

You could extract this piece of code into a seperate method which will be called from within the main program's loop, see the pseudo-code below:

public void Main(string[] args)
{
   while(!doesUserWantToLeave) {
      Console.WriteLine("Please specify the type of conversion you would like to accomplish:" 
      + "\n(Bronze, Silver, 14k Gold, 18k Gold, 22k Gold, Platinum, or Exit):");
      string conversionType = Console.ReadLine();

      Console.WriteLine("What is the weight of the wax model?");
      double waxWeight = double.Parse(Console.ReadLine());

      double weight = ConvertMethod(conversionType, waxWeight);

      Console.WriteLine(string.Format("You need {0} grams of {1}.", weight, conversionType));
   }
}

The method would look as follows. One could either pass strings, or use an enum to define the conversion types.

public double ConvertMethod(string type, double weight)
{
   switch(type) {
      case "Silver":
         return weight * 10.5;
      case "Bronze":
         return weight * 10;

     // etc...
   }
}

Upvotes: -1

David Arno
David Arno

Reputation: 43254

You are only asking for the metal type once. Move the two lines where you prompt for, and receive, the user input inside the while loop:

while (!doesUserWantToLeave)
{
    Console.WriteLine("Please specify the type of conversion you would like to accomplish:" 
        + "\n(Bronze, Silver, 14k Gold, 18k Gold, 22k Gold, Platinum, or Exit):");

    string conversionType = Console.ReadLine();


    if (conversionType == "Bronze")
    {
...

You mention you are new to programming and are aware that you are repeating yourself. You correctly prioritise getting the code working first though. This is good. Having got it working, you should then look at improving the code.

First, the following three lines are repeated after each if and so need only be asked once at the top of the loop:

Console.WriteLine("What is the weight of the wax model?");
wW = Console.ReadLine();
waxWeight = double.Parse(wW);

Next, the last two lines in each if largely repeat, but the only part that changes (the metal name) is known. So they can all be removed and replaced with just one copy at the end of the loop:

Console.WriteLine("You need " + metalWeight + " grams of {0}.", 
                  conversionType.ToLower());
Console.ReadLine();

This then just leaves one line per if. It too repeats itself and the values needed could be stored in Dictionary. Do all that and you could end up with a solution like:

static void Main(string[] args)
{
    bool userWantsToStay = true;
    var conversions = new Dictionary<string, double>
    {
        { "Bronze", 10.0 },
        { "Silver", 10.5 },
        { "14k Gold", 13.5 },
        { "18k Gold", 15.0 },
        { "22k Gold", 17.3 },
        { "Platinum", 21.5 }
    };

    while (userWantsToStay)
    {
        Console.WriteLine("Please specify the type of conversion you would like to accomplish:");
        Console.WriteLine("(Bronze, Silver, 14k Gold, 18k Gold, 22k Gold, Platinum, or Exit):");
        var metalType = Console.ReadLine();

        Console.WriteLine("What is the weight of the wax model?");
        var wW = Console.ReadLine();
        var waxWeight = double.Parse(wW);

        if (conversions.ContainsKey(metalType))
        {
            var metalWeight = waxWeight * conversions[metalType];
            Console.WriteLine("You need {0} grams of {1}.", metalWeight, metalType.ToLower());
            Console.ReadLine();
        }
        else if (metalType == "Exit")
        {
            userWantsToStay = false;
        }
        else
        {
            Console.WriteLine("Sorry! That was an invalid option! Try again");
            Console.ReadLine();
        }
    }
}

This could be improved further (the many ReadLines could likely be removed; you aren't testing whether the weight input is a valid double before parsing), but it'll set you on the right path.

Upvotes: 5

Tim Schmelter
Tim Schmelter

Reputation: 460058

You have to re-assign the user-option at the end of the loop, otherwise it will never change:

while (!doesUserWantToLeave)
{
    if (conversionType == "Bronze")
    {
        //....
    }
    // ...
    else if (conversionType == "Exit")
    {
        doesUserWantToLeave = true;
    }
    else
    {
        Console.WriteLine("Sorry! That was an invalid option!");
    }
    conversionType = Console.ReadLine();
}

So you also have to remove all other Console.ReadLine(); in the loop. You could also use break instead of doesUserWantToLeave = true which leaves the loop.

Upvotes: 3

Related Questions