Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a for loop inside switch/case

Can I use a for loop inside a switch/case?

Example code:

String[,] drinks = new String[,] { { "Cola", "20" }, { "Fanta", "20" }, { "Sprite", "20" }, { "Tuborg", "25" }, { "Carlsberg", "25" } };


switch (menuChoice)
{
  case 0:
    Console.WriteLine("Goodbye!");
    Thread.Sleep(500);
    Environment.Exit(0);
    break;
    for (int i = 0; i < drinksCount; i++)
    {
      case i+1:
      buyDrink(drinks[i,0];
      break;
    }

(More code and methods is in between these)

Basically, I create an array with the drinks this machine sells, and then I want to create a menu where to chose these drinks, but also the ability to add more drinks within the GUI.

Is this even possible?

like image 683
Frederik Nielsen Avatar asked Dec 15 '22 18:12

Frederik Nielsen


1 Answers

You can use loops inside switch statement but not the way you are using it currently. Try to replace your code with below code:

if (menuChoice == 0)
{
    Console.WriteLine("Goodbye!");
    Thread.Sleep(500);
    Environment.Exit(0); 
}
else if (menuChoice > 0 && menuChoice < drinksCount)
{         
    buyDrink(drinks[menuChoice, 0]);
}

ADDED:

As per valuable comments, why don't you just use -1 as menuChoice for Exit, this way:

if (menuChoice == -1)
{
    Console.WriteLine("Goodbye!");
    Thread.Sleep(500);
    Environment.Exit(0);
}
else if (menuChoice > 0 && menuChoice <= drinksCount)
{
    buyDrink(drinks[menuChoice - 1, 0], Convert.ToDouble(drinks[menuChoice - 1, 1]));
}

This way you can call your static method as shown:

static void buyDrink(String drink, double drinkPrice)
like image 55
Furqan Safdar Avatar answered Jan 02 '23 02:01

Furqan Safdar