【发布时间】:2019-10-24 19:16:11
【问题描述】:
所以当我处理数字时,一切正常,只是当我使用非数字条目时。 (我把 cmets 放在了问题所在)
当您输入任何不是数字的内容时,它应该会显示一条错误消息,然后再次提示您输入有效的条目。如果您输入另一个非数字值,而不是停留在循环中,tryParse 会将值更改为 0,因此退出循环并完成程序。我该如何解决这个问题?
我只想在输入0时退出循环,而不是触发tryParse将字符变为0的字符。
我尝试在最后删除 tryParse,但 if 语句中的第一个条件使其为 false,因此直径仍然变为 0。
static void Main()
{
const double MINIMUM_DIAMETER = 12.0;
const double MAXIMUM_DIAMETER = 36.0;
double diameter, radius, area, sliceArea;
string userInput;
Console.Write("\nPlease enter the diameter of your pizza: ");
userInput = Console.ReadLine();
do
{
if (double.TryParse(userInput, out diameter) == false)
{
Console.WriteLine("\nENTRY NON-NUMBERIC ERROR\n");
Console.WriteLine("Pizza must have a numeric diameter. You entered: \"{0}\"\n", userInput);
Console.WriteLine("Please try again.\n");
//**if userInput isn't valid, diameter becomes 0**
}
else
{
if (diameter < MINIMUM_DIAMETER || diameter > MAXIMUM_DIAMETER)
{
//not important
}
else
{
//not important
}
}
Console.Write("\nPlease enter the diameter of your pizza (0 to end program): ");
userInput = Console.ReadLine();
double.TryParse(userInput, out diameter);
Console.Clear();
//**if userInput isn't valid, diameter becomes 0 and exits loop**
} while (diameter != 0);
}
【问题讨论】:
-
你调用了 TryParse() 两次。两次检查返回值。
标签: c# loops do-while tryparse