Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 977
Ninjatix Avatar asked Jul 09 '15 14:07

Ninjatix


People also ask

How do you have an if-else statement with multiple conditions?

The else part of the if/else statement follows the same rules as the if part. If you want to execute multiple statements for the else condition, enclose the code in curly brackets. If you only need to execute a single statement for the else condition, you do not need to use curly brackets.

Can you have multiple if statements in a for loop?

You can put a for loop inside an if statement using a technique called a nested control flow. This is the process of putting a control statement inside of another control statement to execute an action. You can put an if statements inside for loops.

How do you iterate if condition?

The If statement by itself cannot be considered iteration . You can run a code block containing an if statement as many times as you wish, but this doesn't make the if statement an iterator by itself. It's what calls that code block which could stand for iteration.

Can we use if-else in while loop?

Create a for- loop to repeatedly execute statements a fixed number of times. Create a while- loop to execute commands as long as a certain condition is met. Use if-else constructions to change the order of execution.


2 Answers

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.

like image 170
David Arno Avatar answered Sep 19 '22 02:09

David Arno


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.

like image 25
Tim Schmelter Avatar answered Sep 22 '22 02:09

Tim Schmelter