C#循环用户输入并添加他们所做的每个选择的总和



我正试图编写一个程序,向用户询问商品,然后使用字典显示价格。我需要循环该程序,以便它重复它自己;结束";它还需要将用户输入的每个项目的价格加在一起。

我已经被困了好几天了,任何帮助都会很棒。

//dictionary using food and prices 
Dictionary<string, double> FoodMenu = new Dictionary<string, double>();
//add food and prices
FoodMenu.Add("Baja Taco", 4.00);
FoodMenu.Add("Burrito", 7.50);
FoodMenu.Add("Bowl", 8.50);
FoodMenu.Add("Nachos", 11.00);
FoodMenu.Add("Quesadilla", 8.50);
FoodMenu.Add("Super Burrito", 8.50);
FoodMenu.Add("Super Quesadilla", 9.50);
FoodMenu.Add("Taco", 3.00);
FoodMenu.Add("Tortilla Salad", 8.00);
//get order
//food input string
string foodItem = getfooditem();
//use string
static string getfooditem()
{
Console.WriteLine("Item:");
string foodItem = Console.ReadLine();
return foodItem;
}
//check if key exists in food menu
string searchMenu = foodItem;
if (FoodMenu.ContainsKey(searchMenu))
{
Console.WriteLine($"Total: ${FoodMenu[searchMenu]}");
}
else
{
Console.WriteLine($"{searchMenu} does not exist in the menu.");
}

如果你想让程序重复自己,你需要一个循环结构,在这种情况下,需要一个while循环,因为迭代次数不是固定的或已知的。像这样的东西应该可以完成

string userInput = GetFoodItem();
while (userInput != "End")
{
if (foodMenu.ContainsKey(userInput))
{
Console.WriteLine($"Total: ${FoodMenu[userInput]}");
}
else
{
Console.WriteLine($"{userInput} does not exist in the menu");
}
userInput = GetFoodItem();
}

在循环的最后,我们向用户询问另一种食物,然后立即检查。如果它恰好是"End",则while循环将不会执行,并将继续到之后的代码

因为我们经常看到这类问题,我想我应该给出另一种方法:

foreach (var response in
Enumerable
.Repeat(0, int.MaxValue)
.Select(x => Console.ReadLine())
.TakeWhile(x => x != "End")
.Select(x =>
FoodMenu.ContainsKey(x)
? $"Total: ${FoodMenu[x]}" 
: $"{x} does not exist in the menu."))
Console.WriteLine(response);

试试这个:-(

与@MoonMist的第一个答案非常相似,但使用了DoWhile,并与OrdinalIgnoreCase比较CCD_ 1输入以结束程序。

static void Main(string[] args)
{
Dictionary<string, double> FoodMenu = new Dictionary<string, double>();
FoodMenu.Add("Baja Taco", 4.00);
FoodMenu.Add("Burrito", 7.50);
FoodMenu.Add("Bowl", 8.50);
FoodMenu.Add("Nachos", 11.00);
FoodMenu.Add("Quesadilla", 8.50);
FoodMenu.Add("Super Burrito", 8.50);
FoodMenu.Add("Super Quesadilla", 9.50);
FoodMenu.Add("Taco", 3.00);
FoodMenu.Add("Tortilla Salad", 8.00);
string searchKey = string.Empty;
do
{
if (!string.IsNullOrWhiteSpace(searchKey))
{
Console.WriteLine(FoodMenu.ContainsKey(searchKey)
? $"Total: ${FoodMenu[searchKey]}"
: $"{searchKey} does not exist in the menu.");
}
searchKey = GetFoodItem();
} while (!searchKey.Equals("end", StringComparison.OrdinalIgnoreCase));
Console.WriteLine("----End of Program---");
}

//use string
static string GetFoodItem()
{
Console.WriteLine("Item:");
string foodItem = Console.ReadLine();
return foodItem;
}

希望它能有所帮助!非常感谢。

相关内容

最新更新