簡體   English   中英

C# 中的 System.FormatException

[英]System.FormatException in C#

在我嘗試為銷售變量分配值的行中的每種情況下,我都不斷收到 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();
      }
   }
}

在我嘗試為銷售變量分配值的行中的每種情況下,我都不斷收到 FormatException。 有誰知道我做錯了什么?

如果字符串(從Console.ReadLine()返回)不是有效數字,則Convert.ToDouble方法將引發FormatException

通常,如果要解析用戶輸入,最好改用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

雖然里德的回答很棒,但這不是問題所在。

實際發生的情況與相同

Console.Read 只讀取“回車第二部分”並返回“”。 這就是轉換失敗的原因。

代替

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

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

代替

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM