逆ポーランド記法を実行する関数を作成できました。メソッドの構造は問題ありません。私が直面している2つの問題は、ユーザーが入力した数式を取得してtextBox1
、に回答(数式=回答)を表示する方法textBox2
です。textBox1
変数に割り当てましたrpnValue
が、エラーメッセージが表示されますA field initializer cannot reference the non-static field, method, or property 'modified_rpn.Form1.textBox1'
。では、もう一度、ユーザーが入力した数式を取得しtextBox1
て、複数行の `textBox2に回答(数式=回答)を表示するにはどうすればよいですか?
コード
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);
}
}
}