2014-09-05 24 views
-8

我不知道如何獲得異常工作使例外工作

該程序應提示爲整數英鎊轉換和匯率。然後它應該以類似於下面的輸出的方式顯示follars的平等數量。

第一部分的工作原理在這裏是我的代碼

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 

namespace CurrencyConvertor 
{ 
    class Program 
    { 
    static void Main(string[] args) 
    { 
     CurrencyConvertor(); 
     Console.ReadLine(); 
    } 

    private static void CurrencyConvertor() 
    { 
     int ivalue; 
     float exchange; 
     float results; 
     bool valid; 

     Console.WriteLine(" please enter a whole number of pounds"); 

     do 
     { 
     try 
     { 
      ivalue = int.Parse(Console.ReadLine()); 
      Console.WriteLine(" pounds entered : " + ivalue); 

      Console.WriteLine("please enter the exchange rate"); 
      exchange = float.Parse(Console.ReadLine()); 
      Console.WriteLine(" exchange rate is " + exchange); 

      results = ivalue * exchange; 
      Console.WriteLine(" £ " + ivalue + " is equivlent to" + " $ {0:N}", results); 
      valid = true; 
     } 
     catch 
     { 
      Console.WriteLine("unable to convert to integer"); 
      Console.WriteLine(" Try again- ensure you enter a number"); 
      valid = false; 
     } 
     } while (valid == false); 
     Console.ReadLine(); 
    } 
    } 
} 

兩個輸入應該被確認,以確保用戶輸入適當的數據類型 - 低於輸出示出預期的輸出,如果用戶進入非數值數據。

所以應該顯示

please enter an integer 
try again - ensure you enter an integer 
12 
pounds entered 12 
please enter an exchange rate 
asd 
unable to convert to a number 
try again - ensure you enter a number 
1.56 
exchange rate is 1:56 
£12.00 is equivalent to $18.72 

我似乎無法得到它的顯示錯誤消息的匯率說「無法轉換爲數字」

+0

你試過調試你的代碼嗎?哪條線似乎失敗? – 2014-09-05 09:59:27

+0

請擺脫所有空行 – thumbmunkeys 2014-09-05 09:59:38

+0

應該有另一個例外,所以它應該顯示'console.writelinne(「無法轉化爲數字」)'@YuvalItzchakov不知道它在哪裏去? – BlairHeid 2014-09-05 10:01:41

回答

1

有在你的代碼中的一些缺陷:

  • 你應該更喜歡int.TryParse而不是Parse。一個Exception應該是一個意想不到的行爲,你必須以某種方式作出反應。用戶輸入不是意外的,你知道有可能使用輸入無效的數據,你可以/不得不驗證。

  • 當您使用異常時,您不應該一次捕獲所有異常,而應該知道如何反應的某種類型的異常。 int.Parse本身會拋出三種異常(請參見http://msdn.microsoft.com/de-de/library/b3h1hf19(v=vs.110).aspx),您可以從系統本身獲取其他一些異常。你的代碼應該趕上FormatException而不是全部。無論如何,如果你只是想修復你的代碼,你可以解決你的問題,使用兩個單獨的try .. catch塊與分離的錯誤消息。

1

例外的是沒有趕上例外 - 的東西,你不希望發生,但可能

您應該使用TryParse方法,而不是

while(!int.TryParse(Console.ReadLine(), out ivalue) 
{ 
    Console.WriteLine("Thats not a number, try again"); 
}