在我尝试为 sale 变量分配值的行中的每种情况下,我不断收到 FormatException。有人知道我做错了什么吗?我应该将此控制台程序作为学习循环的作业,但我正在了解更多有关其他内容的信息。它应该根据每笔销售的 10% 佣金来记录销售人员的佣金。无论如何,这是代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TubSales
{
class Program
{
static void Main(string[] args)
{
char initial;
const double COMM_INT = 0.10;
double sale, aComm = 0, bComm = 0, eComm = 0;
Console.Write("Enter 'A' for Andrea, 'B' for Brittany,\n'E' for Eric, or 'Z' to quit >> ");
initial = Convert.ToChar(Console.Read());
while (initial != 'z' && initial != 'Z')
{
switch (initial)
{
case 'a':
case 'A':
Console.Write("Enter the sales for Andrea >> ");
sale = Convert.ToDouble(Console.ReadLine());
aComm = aComm + COMM_INT * sale;
break;
case 'b':
case 'B':
Console.Write("Enter the sales for Brittany >> ");
sale = Convert.ToDouble(Console.ReadLine());
bComm = bComm + COMM_INT * sale;
break;
case 'e':
case 'E':
Console.Write("Enter the sales for Eric >> ");
sale = Convert.ToDouble(Console.ReadLine());
eComm = eComm + COMM_INT * sale;
break;
default:
Console.WriteLine("You did not enter a valid initial");
break;
}
Console.Write("Enter 'A' for Andrea, 'B' for Brittany, or 'E' for Eric >> ");
initial = (char)Console.Read();
}
Console.WriteLine("Andrea had {0}, Brittany had {1}, and Eric had {2} in commissions.", aComm.ToString("C"), bComm.ToString("C"), eComm.ToString("C"));
Console.Write("Press any key to exit... ");
Console.ReadKey();
}
}
}
在我尝试为 sale 变量分配值的行中的每种情况下,我不断收到 FormatException。有人知道我做错了什么吗?
The 转换为双精度 http://msdn.microsoft.com/en-us/library/zh1hkw6k.aspx方法会提出一个FormatException
如果字符串(从返回Console.ReadLine()
) 不是有效数字。
通常,如果您想解析用户输入,最好使用Double.TryParse http://msdn.microsoft.com/en-us/library/system.double.tryparse.aspx相反,因为这可以让您确定输入是否是有效数字without捕获异常。
这通常看起来像这样:
Console.Write("Enter the sales for Andrea >> ");
while (!double.TryParse(Console.ReadLine(), out sale))
{
Console.WriteLine("Value entered was not a valid number.");
Console.Write("Enter the sales for Andrea >> ");
}
// Once you get here, "sale" will be set appropriately
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)