您的代码中存在一些逻辑缺陷,您必须加以修复。请看cmets:
Console.Write("What is the price?");
price = decimal.Parse(Console.ReadLine()); // you're already parsing the user-input into
// a decimal. This is somewhat problematic, because if the user enters "foo" instead
// of "123" the attempt to parse the input will fail
double pricenumber;
while (!double.TryParse(price, out pricenumber)) // the variable "price" already contains
// a parsed decimal. That's what you did some lines above. "TryParse" expects a string to
// be parsed whereas you're committing the parsed decimal
{
Console.WriteLine("You've not entered a price.\r\nPlease enter a price");
price = decimal.Parse(Console.ReadLine());
}
所以你应该做的是将用户输入保持为字符串,直到你尝试解析它:
Console.Write("What is the price?");
string input = Console.ReadLine(); // keep as string
double pricenumber;
while (!decimal.TryParse(input, out pricenumber))
{
Console.WriteLine("You've not entered a price.\r\nPlease enter a price");
input = Console.ReadLine();
}
您的其他尝试也是如此。再次,请查看 cmets:
Console.Write("How many were you planning on purchasing?");
amount = decimal.Parse(Console.ReadLine()); // you're already parsing the string into a
// decimal
while (amount == string.Empty) // as you can't compare a decimal with a string, this
// creates an error
{
Console.WriteLine("You cannot leave this blank.\r\nPlease enter how many are needed:");
amount = decimal.Parse(Console.ReadLine());
}
你可以用上面的方法解决它:
Console.Write("How many were you planning on purchasing?");
input = Console.ReadLine(); // again, keep as string
while (!decimal.TryParse(input, out amount))
{
Console.WriteLine("You cannot leave this blank.\r\nPlease enter how many are needed:");
input = Console.ReadLine();
}
如果还有进一步优化的空间,您可以并且应该将该逻辑放入单独的方法中,因为代码几乎相同并且会导致重复。
private static decimal GetParsedInput(string question, string noticeOnFailed)
{
Console.Write(question);
input = Console.ReadLine();
decimal result;
while (!decimal.TryParse(input, out result))
{
Console.WriteLine(questionOnFailed);
input = Console.ReadLine();
}
return result;
}
用法:
decimal price = GetParsedInput(
"What is the price?",
"You've not entered a price.\r\nPlease enter a price:");
decimal amount = GetParsedInput(
"How many were you planning on purchasing?",
"You cannot leave this blank.\r\nPlease enter how many are needed:");