C#中的System.FormatException

时间:2012-05-14 18:04:47

标签: c# formatexception

我在尝试为销售变量分配值的行中的每个案例中都持续获得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();
      }
   }
}

3 个答案:

答案 0 :(得分:5)

  

我在尝试为销售变量分配值的行中的每个案例中都持续获得FormatException。谁知道我做错了什么?

如果字符串(从FormatException返回)不是有效数字,Convert.ToDouble方法将引发Console.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

答案 1 :(得分:1)

虽然里德的答案很棒,但这不是问题所在。

真正发生的情况与this one

的情况相同

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

替换

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

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

答案 2 :(得分:0)

替换

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

initial = Convert.ToChar(Console.ReadLine().FirstOrDefault());