[英]System.FormatException occurred in mscorlib.dll when converting it int32
[英]System.FormatException on Int32 from string
当我获取区域输入时,我正在获取System.FormatException。 尽快告诉我解决方案。
double price;
int region;
string p;
Console.Write("Enter the total price of items : ");
price= Console.Read();
Console.WriteLine("Select the your region.");
Console.WriteLine("1 : Pakistan");
Console.WriteLine("2 : UK");
Console.WriteLine("3 : Cortia");
p= Console.ReadLine();
region = Convert.ToInt32(p);
您的价格是double类型,但是您尝试将控制台输入的值作为字符串分配,将其转换为double可以解决问题,还可以使用TryParse进行转换,这会在转换期间捕获所有异常。
double price;
int region;
Console.Write("Enter the total price of items : ");
double.TryParse(Console.ReadLine(), out price);
Console.WriteLine("Select the your region.");
Console.WriteLine("1 : Pakistan");
Console.WriteLine("2 : UK");
Console.WriteLine("3 : Cortia");
int.TryParse(Console.ReadLine(), out region);
您可以使用TryParse,然后检查是否可以将输入转换为int值。
您也可以在价格中使用TryParse。
double price;
int region;
string p;
Console.Write("Enter the total price of items : ");
price = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Select the your region.");
Console.WriteLine("1 : Pakistan");
Console.WriteLine("2 : UK");
Console.WriteLine("3 : Cortia");
p = Console.ReadLine();
if (!int.TryParse(p, out region))
{
//error handle.
}
else
{
//at this point, the region value already has the value of p;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.