2016-09-14 51 views
-1

以下代碼正在用作十六進制計算器(0-9,A-F)上的16位數字按鈕的通用事件處理程序。如何讓我的StringBuilder正確追加?

以下說明定義我需要完成的事情:

如果計算器處於顯示模式時,按下一個數字,這個數字就更換顯示的當前內容,並放置在輸入模式下的計算器。如果計算器處於輸入模式,則有三種情況:

  • 如果顯示內容爲「0」,則按下的按鈕上的數字將替換顯示內容。
  • 否則,如果顯示內容少於八個字符(因爲我們正在處理32位字),則按下的按鈕上的數字將被添加到顯示內容中。
  • 否則,按鈕被忽略。

在我的計算器上按下一個按鈕將正確更新顯示。但是,如果我按另一個按鈕,而不是將新的字符附加到StringBuilder上,它將顯示最後一個按鈕的雙字符。例如。一次按'C'將顯示'C'。按'C'然後說'8'將顯示'88'。我的問題在哪裏?

public void ProcessClick(object sender, EventArgs e) 
    { 
     StringBuilder _button = new StringBuilder(); 
     _button.Append(((Button)sender).Text); 

     if (mode) 
     { 
      uxDisplay.Text = _button.ToString(); 
      mode = false; 
     } 
     else 
     { 
      if (uxDisplay.Text == "0") 
      { 
       uxDisplay.Text = _button.ToString(); 
      } 
      else if (uxDisplay.Text.Length < 8) 
      { 
       uxDisplay.Text = _button.Append(((Button)sender).Text).ToString(); 
      } 
      else 
      { 
       return; 
      } 
     } 
    } 

回答

2

您似乎要追加兩次值sender.Text

這裏:

_button.Append(((Button)sender).Text); 

這裏:

uxDisplay.Text = _button.Append(((Button)sender).Text).ToString(); 

您也從uxDisplay創建每次調用一個新的StringBuilder到過程,因此不堅持的最後一個值(除控制)

如何喜歡簡單的東西:

... 
else if (uxDisplay.Text.Length < 8) 
{ 
    uxDisplay.Text += ((Button)sender).Text; 
} 

您只添加了少量的字符串,因此您不會真正獲得使用StringBuilder的所有性能(尤其是在每次調用時創建新的字符串! :P)

0

你正在將被按下的按鈕文本附加到你的StringBuilder對象上,這就是你獲得兩倍字符的原因。

你可以用這樣簡單的東西去:

public void ProcessClick(object sender, EventArgs e) 
{ 
    if (mode) 
    { 
     uxDisplay.Text = _button.ToString(); 
     mode = false; 
    } 
    else 
    { 
     if (uxDisplay.Text == "0") 
     { 
      uxDisplay.Text = _button.ToString(); 
     } 
     else if (uxDisplay.Text.Length < 8) 
     { 
      uxDisplay.Text += ((Button)sender).Text; 
     } 
     else 
     { 
      return; 
     } 
    } 
}