2017-04-01 54 views
-1

我正在使用C#中的簡單計算器控制檯應用程序,並且要檢查用戶是否輸入了字符串而不是數字/小數。相反,我得到一個破壞程序的System.Format異常。如果看到字符串字符,我不確定如何告訴程序不要中斷。我使用while while循環來重新提示用戶,如果他們輸入負數或任何其他無效值。在將C#中的字符串轉換爲雙精度數據後檢查輸入是否是字符串

這裏是我的代碼:

using System; 


namespace Calc 
{ 
    public class Calc 
    { 
     public static void Main() 
     { 

     ///Declare variables 
     double p,r,y; 
     string input1, input2, input3; 



     ///Prompt user to reenter value if the input is illegal 
     do 
     { 
      ///Prompt the user for the principal 
      Console.Write("Enter the principal: "); 
      input1 = Console.ReadLine(); 
      p = double.Parse(input1); 
     } while(p < 0); 


     ///Prompt the user for the rate 
     Console.Write("Enter the rate: "); 
     input2 = Console.ReadLine(); 
     r = double.Parse(input2); 

     ///Prompt user to reenter value if the input is illegal 
     do 
     { 
      ///Prompt the user for the rate 
      Console.Write("Enter the rate: "); 
      input2 = Console.ReadLine(); 
      r = double.Parse(input2); 

     } while(r < 0); 



     ///Prompt user to reenter value if the input is illegal 
     do 
     { 
      ///Prompt the user for the number of years 
      Console.Write("Enter the number of years: "); 
      input3 = Console.ReadLine(); 
      y = double.Parse(input3); 
     } while (y < 0); 

     ///Calculate the user input using the mortgage rate formula 
     double p1 = (r/1200.0); 
     double m = y * 12; 
     double nm = 0 - m; 
     double month = p * p1/(1 - System.Math.Pow((1 + p1), nm)); 



     //Output the result of the monthly payment 
     Console.WriteLine(String.Format("The amount of the monthly payment is: {0}{1:0.00}", "$", month)); 
     Console.WriteLine(); 
     Console.WriteLine("Press Enter to end the calculator program. . ."); 
     Console.Read(); 
    } 
} 
} 
+0

見標記複製。無論您是處理「int」,「double」,「DateTime」還是任何其他可解析類型,都可以使用完全相同的通知。另請參閱討論http://stackoverflow.com/questions/531397/handling-exceptions-vs-preventing-them-from-occuring-in-the-first-place-c-sha –

+0

其他相關和有用的職位包括http: //stackoverflow.com/questions/150114/parsing-performance-if-tryparse-try-catch,http://stackoverflow.com/questions/12768625/cannot-implicitly-convert-type-string-to-double-issue,和http://stackoverflow.com/questions/8122604/check-if-string-can-be-converted-to-a-given-type-in​​-c-sharp –

回答

3

您可以使用TryParse返回一個bool說,如果轉換成功:

bool IsValid = double.TryParse(input2,out r); 

現在,您可以檢查是否IsValid返回true那麼它是一個有效值到來,否則可以提示用戶重新輸入:

bool IsValid = false; 
    ///Prompt user to reenter value if the input is illegal 
    do 
    { 
     ///Prompt the user for the rate 
     Console.Write("Enter the rate: "); 
     input2 = Console.ReadLine(); 
     IsValid = double.TryParse(input2, out r); 

    } while(!IsValid && r < 0); 
+0

這個解釋對我來說最合適 – user2101463

0

Double.TryParse使用

許多其雙精度 浮點數等效的字符串表示形式轉換。返回值指示 轉換是成功還是失敗。

這種方式,你可以得到,如果數字是使用它之前兌換...

相關問題