0

在我尝试为销售变量分配值的每一种情况下,我都会收到 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();
      }
   }
}
4

3 回答 3

5

在我尝试为销售变量分配值的每一种情况下,我都会收到 FormatException。有人知道我在做什么错吗?

如果字符串(从 返回)不是有效数字,则Convert.ToDouble方法将引发 a 。FormatExceptionConsole.ReadLine()

通常,如果您想解析用户输入,最好使用Double.TryParse,因为这可以让您确定输入是否为有效数字而不会捕获异常。

这通常看起来像:

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
于 2012-05-14T18:10:04.883 回答
1

虽然 Reed 的答案很好,但这不是问题所在。

真正发生的是和这个一样的情况

Console.Read 只读取“回车的第二部分”并返回“”。这就是转换失败的原因。

代替

initial = Convert.ToChar(Console.Read());

initial = Convert.ToChar(Console.ReadLine());
于 2012-05-14T18:23:05.277 回答
0

代替

initial = Convert.ToChar(Console.Read());

initial = Convert.ToChar(Console.ReadLine().FirstOrDefault());
于 2012-05-14T18:22:13.390 回答