C# 如何在控制台应用程序中实现简单的基于文本的菜单?
我想在折扣价格计算器中有一个选项,我是为了好玩而写的,我想重新开始这个程序,我想知道如何才能最好地去做它。我想让它说一些类似的话:“你想输入另一个价格吗?”如果用户说“是”或“是”或“否”等,要么重新启动程序,要么退出。我可能应该使用if循环,对吗?有人能告诉我如何实现它吗?或者给我指出正确的方向?我还觉得我应该重新编写程序,使其具有方法,但我不熟悉CC# 如何在控制台应用程序中实现简单的基于文本的菜单?,c#,C#,我想在折扣价格计算器中有一个选项,我是为了好玩而写的,我想重新开始这个程序,我想知道如何才能最好地去做它。我想让它说一些类似的话:“你想输入另一个价格吗?”如果用户说“是”或“是”或“否”等,要么重新启动程序,要么退出。我可能应该使用if循环,对吗?有人能告诉我如何实现它吗?或者给我指出正确的方向?我还觉得我应该重新编写程序,使其具有方法,但我不熟悉C 只要用户在程序末尾指定y或yes(不区分大小写),以下循环将循环执行 static void Main(string[] args) {
只要用户在程序末尾指定
y
或yes
(不区分大小写),以下循环将循环执行
static void Main(string[] args)
{
string price, discount;
decimal discountedPrice, savedAmount;
bool startAgain = true;
string line;
// Loop again every time the startAgain flag is true.
while (startAgain)
{
//Receiving the price as input
Console.WriteLine("Please enter the price of the item.");
price = Console.ReadLine();
decimal numPrice = decimal.Parse(price);
//Receiving the discount as input
Console.WriteLine("Please enter the discount that you wish to apply");
discount = Console.ReadLine();
//Receiving discount from input, divide by 100 to convert to percentile
decimal numDiscount = decimal.Parse(discount) / 100;
//Calculate the discounted price with price - (price * discount)
discountedPrice = numPrice - (numPrice * numDiscount);
//Calculate the amount of money they saved
savedAmount = numPrice - discountedPrice;
Console.WriteLine("The discounted price of this item is: ${0}\nYou saved: ${1}", discountedPrice, savedAmount);
Console.ReadLine();
// Ask if the user wants to submit another price.
Console.WriteLine("Would you like to enter another price?");
// Record the spaceless, lower-case answer.
line = Console.ReadLine().ToLowerCase().Trim();
// Set the startAgain flag to true only if the line was "y" or "yes".
startAgain = line == "y" || line == "yes";
}
}
您可以这样做:
static void Main(string[] args)
{
string resp = "";
string price, discount;
decimal discountedPrice, savedAmount;
do {
.... // your previous code here
....
Console.WriteLine("The discounted price of this item is: ${0}\nYou saved: ${1}", discountedPrice, savedAmount);
Console.WriteLine("Another item?");
string resp = Console.ReadLine().ToLower();
}
while (resp == "y" || resp == "yes");
Console.ReadLine();
}
这只是一个粗略的样本
string input = null;
do {
//your code
Console.WriteLine("Would you like to insert another price?");
input = Console.ReadLine();
if(input.ToLower() != "y" || //if responce to the question is not 'y' or 'yes', break the loop
input.ToLower() != "yes")
break;
}while(true);
编辑
这个程序会插入一个价格,直到用户确认他想插入一个新的价格,否则就退出。我觉得这很好。没有足够的代码需要使用方法,除非你想添加其他内容?你应该试着按照你说的去做。看起来其他人的答案可以解决你的问题。我只是想让您知道应该使用decimal.TryParse而不是decimal.Parse。这样,如果输入了无效的小数,您的程序就不会在您身上爆炸。
string input = null;
do {
//your code
Console.WriteLine("Would you like to insert another price?");
input = Console.ReadLine();
if(input.ToLower() != "y" || //if responce to the question is not 'y' or 'yes', break the loop
input.ToLower() != "yes")
break;
}while(true);