我正在使用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();
}
}
}
見標記複製。無論您是處理「int」,「double」,「DateTime」還是任何其他可解析類型,都可以使用完全相同的通知。另請參閱討論http://stackoverflow.com/questions/531397/handling-exceptions-vs-preventing-them-from-occuring-in-the-first-place-c-sha –
其他相關和有用的職位包括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 –