如何解决如何为 Switch 语句创建循环,直到用户在 C# 中输入特定单词
我正在尝试创建一个“咖啡店”,控制台会继续询问用户他们想要什么,直到他们输入完成为止。使用我包含的代码,它会询问您想要什么,然后执行一次 while 循环。我对此很陌生,因此将不胜感激。
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,and brownie!");
break;
}
break;
}
while (food != "finish");
Console.Read();
}
解决方法
我修改了你的代码:
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,and brownie!");
break;
}
}
while (food != "finish");
Console.Read();
}
此代码按您的预期工作
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。