2012-12-01 45 views
0

我能夠創建一個函數來執行反向波蘭表示法。該方法的結構很好,我遇到的兩個問題是如何獲取用戶在textBox1中輸入的公式,並在textBox2上顯示答案(公式=答案)。我已將textBox1分配給變量rpnValue,但它給出了錯誤消息A field initializer cannot reference the non-static field, method, or property 'modified_rpn.Form1.textBox1'。所以我再次如何獲取用戶在textBox1中輸入的公式,並在多行textBox2上顯示答案(formula = answer)?反向波蘭表示法計算器:抓取輸入並顯示結果

代碼

namespace rpn 
{ 
    public partial class Form1 : Form 
    { 
     public Form1() 
     { 
      InitializeComponent(); 
     } 

     string rpnValue = textBox1.Text; 

     private void RPNCalc(rpnValue) 
     { 
      Stack<int> stackCreated = new Stack<int>(); 
      try 
      { 
       var tokens = rpnValue.Replace("(", " ").Replace(")", " ") 
            .Split().Where(s => !String.IsNullOrWhiteSpace(s)); 
       foreach (var t in tokens) 
       { 
        try 
        { 
         stackCreated.Push(Convert.ToInt32(t)); 
        } 
        catch 
        { 
         int store1 = stackCreated.Pop(); 
         int store2 = stackCreated.Pop(); 
         switch (t) 
         { 
          case "+": store2 += store1; break; 
          case "-": store2 -= store1; break; 
          case "*": store2 *= store1; break; 
          case "/": store2 /= store1; break; 
          case "%": store2 %= store1; break; 
          case "^": store2 = (int)Math.Pow(store1, store2); break; 
          default: throw new Exception(); 
         } 
         stackCreated.Push(store2); 
        } 
       } 

       if (stackCreated.Count != 1) 
        MessageBox.Show("Please check the input"); 
       else 
        textBox1.Text = stackCreated.Pop().ToString(); 

      } 
      catch 
      { 
       MessageBox.Show("Please check the input"); 
      } 

      textBox2.AppendText(rpnValue); 
      textBox1.Clear(); 
     } 


     private void button1_Click(object sender, EventArgs e) 
     { 
      RPNCalc(textBox1, textBox2); 
     } 
    } 
} 

enter image description here

回答

0

您需要移動這條線:

string rpnValue = textBox1.Text; 

方法或函數內部。你有一個方法或功能以外,你不能這樣做。

1

三個問題與您的代碼:

首先是,它的不合邏輯的線訪問一個文本框的文本值:string rpnValue = textBox1.text其次,

private void button1_Click(object sender, EventArgs e) 
     { 
      RPNCalc(textBox1, textBox2); 
     } 

在這裏,你可以看到你提供當它實際上只期待一個時,2個參數到RPNCalc()。你需要認真理解你在這裏做什麼。此外,您不能在定義該方法期間指定提供給RPNCalc()的值的「類型」。

重新閱讀你的C#書:-)

+0

+1謝謝你的建議。你能幫我根據你的回答修復代碼嗎? – techAddict82