[英]How to Create a Loop for a Switch Statement That Repeats Until the User Types a Specific Word In C#
I am trying to make a "coffee shop" where the console continues to ask the person what they want until they type finish.我正在尝试制作一个“咖啡店”,控制台会继续询问他们想要什么,直到他们输入完成。 With the code I included, it asks what you want and then does the while loop once.
使用我包含的代码,它会询问您想要什么,然后执行一次 while 循环。 I am very new to this so any help would be appreciated.
我对此很陌生,因此将不胜感激。
static void Main(string[] args)
{
int totalCost = 0;
Console.WriteLine("Hi, what would you like to buy?");
Console.WriteLine("Please type your choice; the menu is coffee, cookie, latte, muffin, tea, and brownie!");
string food = Console.ReadLine();
string v = "Thank you, that will cost $";
do
{
food = Console.ReadLine();
switch (food)
{
case "coffee":
Console.WriteLine(v + "4");
totalCost = totalCost + 4;
break;
case "cookie":
Console.WriteLine(v + "2");
totalCost = totalCost + 2;
break;
case "latte":
Console.WriteLine(v + "5");
totalCost = totalCost + 5;
break;
case "muffin":
Console.Write(v + "3");
totalCost = totalCost + 3;
break;
case "tea":
Console.WriteLine(v + "2");
totalCost = totalCost + 2;
break;
case "brownie":
Console.WriteLine(v + "100");
totalCost = totalCost + 100;
break;
case "finish":
Console.WriteLine("Your total is $" + totalCost + ". Thank you for your purchase - enjoy!");
break;
default:
Console.WriteLine("Hi, what would you like to buy?");
Console.WriteLine("Please type your choice; the menu is coffee, cookie, latte, muffin, tea, and brownie!");
break;
}
break;
}
while (food != "finish");
Console.Read();
}
I modified your code:我修改了你的代码:
static void Main(string[] args)
{
int totalCost = 0;
Console.WriteLine("Hi, what would you like to buy?");
Console.WriteLine("Please type your choice; the menu is coffee, cookie, latte, muffin, tea, and brownie!");
string food = "";
string v = "Thank you, that will cost $";
do
{
food = Console.ReadLine();
switch (food)
{
case "coffee":
Console.WriteLine(v + "4");
totalCost = totalCost + 4;
break;
case "cookie":
Console.WriteLine(v + "2");
totalCost = totalCost + 2;
break;
case "latte":
Console.WriteLine(v + "5");
totalCost = totalCost + 5;
break;
case "muffin":
Console.Write(v + "3");
totalCost = totalCost + 3;
break;
case "tea":
Console.WriteLine(v + "2");
totalCost = totalCost + 2;
break;
case "brownie":
Console.WriteLine(v + "100");
totalCost = totalCost + 100;
break;
case "finish":
Console.WriteLine("Your total is $" + totalCost + ". Thank you for your purchase - enjoy!");
break;
default:
Console.WriteLine("Hi, what would you like to buy?");
Console.WriteLine("Please type your choice; the menu is coffee, cookie, latte, muffin, tea, and brownie!");
break;
}
}
while (food != "finish");
Console.Read();
}
This code works as you expect此代码按您的预期工作
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.