2012-12-01 46 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