我能夠創建一個函數來執行反向波蘭表示法。該方法的結構很好,我遇到的兩個問題是如何獲取用戶在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);
}
}
}
+1謝謝你的建議。你能幫我根據你的回答修復代碼嗎? – techAddict82