[英]C# FormatException Unhandled
我正在使用Microsoft Visual C#2010 Express。 我目前正在嘗試讓我的計算器進行加法和減法,但是我一直收到此錯誤? 我在整個計算器中都使用switch語句。
private void Add_Click(object sender, EventArgs e)
{
//Storing the number on display in variables total1 for further use
//Making addition happen before = is clicked
total1 = total1 + double.Parse(textDisplay.Text);
textDisplay.Text = textDisplay.Text + Add.Text;
theOperator = "+";
}
private void Subtract_Click(object sender, EventArgs e)
{
total1 = total1 + double.Parse(textDisplay.Text);
textDisplay.Clear();
theOperator = "-";
}
private void Equals_Click(object sender, EventArgs e)
{
switch(theOperator)
{
case "+": //Addition
total1 = total1 + double.Parse(textDisplay.Text);---> error in this line
textDisplay.Text = result.ToString();
total1 = 0;
break;
case "-": //Subtraction
result = total1 - double.Parse(textDisplay.Text);--->error in this line
textDisplay.Text = result.ToString();
total1 = 0;
break;
在問題線上,您具有:
double.Parse(textDisplay.Text)
但是在您的Add_Click
方法中,您可以這樣:
textDisplay.Text = textDisplay.Text + Add.Text;
我假設您的“ Add
按鈕標簽不是數字(可能是Add
或+
)。 因此,當您運行上面的行時,您將獲得類似以下內容的信息:
當您將其傳遞給double.Parse
時,這將導致異常,因為此函數不接受錯誤的輸入(因此,除非textDisplay.Text
是數字,否則它將產生錯誤)。 如果要測試輸入錯誤,則可以使用double.TryParse
。
這是有關如何測試輸入錯誤的示例:
private void Equals_Click(object sender, EventArgs e)
{
// Remove the operator from the value we want to process.
// It is expected this will be at the end.
var userValue = textDisplay.Text;
if (userValue.EndsWith(theOperator))
{
userValue = userValue.Substring(0, userValue.Length - theOperator.Length).Trim();
}
// Test for valid input.
// Test our "userValue" variable which has the pending operator removed.
double value;
if (!double.TryParse(userValue, out value))
{
// Invalid input.
// Alert the user and then exit this method.
MessageBox.Show("A number was not entered.");
return;
}
// If we get here, the "value" variable is a valid number.
// Use it for calculations.
...
編輯
附帶說明一下,您確實在使用和重置OP中的result
和total1
方面存在一些邏輯問題。 我不會為您做家庭作業,但是最好檢查一下這些變量的用法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.