jeudi 18 juin 2015

c# nested if/else in a for loop

I have a nested if/else statement in a for loop to determine whether or a a value is valid with an array value. It returns all values just fine, however if the IF is correct, it still does the else an additional three times. I thought once it was equal one time, it would stop, but I suppose I am missing something here.

Any thoughts?

string sectionChoice;
int ticketQuantity;
double ticketPrice, totalCost;
string[] section = { "orchestra", "mezzanine", "balcony", "general" };
double[] price = { 125.25, 62.00, 35.75, 55.50 };
bool isValidSection = false;

sectionChoice = GetSection();
ticketQuantity = GetQuantity();

for (int x = 0; x < section.Length; ++x)
{
        if (sectionChoice == section[x])
        {
            isValidSection = true;
            ticketPrice = price[x];

            totalCost = CalcTicketCost(ticketPrice, ticketQuantity);
            Console.Write("\n\nTotal cost for the tickets are: {0:c2}", totalCost);
        }
        else
            Console.Write("\n\nInvalid entry, {0} does not exsist", sectionChoice);        
}

When it is valid, it returns something like this:

Your price is 32.50. Invalid entry, x does not exsist Invalid entry, x does not exsist Invalid entry, x does not exsist

Aucun commentaire:

Enregistrer un commentaire