我目前正在使用反向波兰符号计算器。它功能齐全,但我遇到了文本输入问题,然后将用于计算值。如果引入类似的公式,程序就会中断( 8 5 + ) 6 * =
。有没有办法简单地忽略输入值中显示的任何括号?此外,我的程序确实会根据每个数字之间的空格进行拆分,但是如果我要在操作数或括号之间添加空格,它也会中断:(8 5 +)6 * =
。如果它是无效的公式12 + =
(缺少数字),我想忽略它们并在输出文本框中显示一条错误消息。
旁注:每个公式都由结尾触发=
。
代码
namespace rpncalc
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private string inputValue = "";
private void RPNCalc(string rpnValue)
{
Stack<int> stackCreated = new Stack<int>();
stackCreated.Clear();
string[] inputArray = rpnValue.Split();
int end = inputArray.Length - 1;
int numInput;
int i = 0;
do
{
if ("=+-*/%^".IndexOf(inputArray[i]) == -1)
{
try
{
numInput = Convert.ToInt32(inputArray[i]);
stackCreated.Push(numInput);
}
catch
{
MessageBox.Show("Please check the input");
}
}
else if (inputArray[i]== "+")
{
try
{
int store1 = stackCreated.Pop();
int store2 = stackCreated.Pop();
stackCreated.Push(store2 + store1);
}
catch
{
}
}
else if (inputArray[i]== "-")
{
try
{
int store1 = stackCreated.Pop();
int store2 = stackCreated.Pop();
stackCreated.Push(store2 - store1);
}
catch
{
}
}
else if (inputArray[i]== "%")
{
try
{
int store1 = stackCreated.Pop();
int store2 = stackCreated.Pop();
stackCreated.Push(store2 % store1);
}
catch
{
}
}
else if (inputArray[i]== "*")
{
try
{
int store1 = stackCreated.Pop();
int store2 = stackCreated.Pop();
stackCreated.Push(store2 * store1);
}
catch
{
}
}
else if (inputArray[i]== "/")
{
try
{
int store1 = stackCreated.Pop();
int store2 = stackCreated.Pop();
stackCreated.Push(store2 / store1);
}
catch
{
}
}
else if (inputArray[i] == "^")
{
try
{
int store1 = stackCreated.Pop();
int store2 = stackCreated.Pop();
stackCreated.Push((int)Math.Pow(store1, store2));
}
catch
{
}
}
}
while(i++ < end && inputArray[i]!= "=" && stackCreated.Count != 0);
string result = inputValue + " " + stackCreated.Pop().ToString() + Environment.NewLine;
TxtOutputBox.AppendText(result);
TxtInputBox.Clear();
}
private void TxtOutputBox_TextChanged(object sender, EventArgs e)
{
}
private void Btn_Calc_Click(object sender, EventArgs e)
{
inputValue = TxtInputBox.Text + " ";
RPNCalc(inputValue);
}
}
}