I made a Infix
to Postfix
convertor, and thought it worked, but when I went back and showed it to my teacher one of the examples he tested turns out wrong. :|
I would be grateful if someone could help me on this matter, and let me know what's wrong.
I skipped the parts about the buttons for inputting numbers and only posted the rest of it,
private void button20_Click(object sender, EventArgs e)
{
try
{
string infix = textBox1.Text;
infixTopostfix obj = new infixTopostfix(infix);
textBox1.Text = string.Empty;
Console.WriteLine("{0} is the Postfix of {1}", obj.createPrifex(), infix);
}
catch (Exception e1)
{
Console.WriteLine(e1.ToString());
}
}
The part above is for redirecting a console.writeline
to my text box and its the button that does all the works and gives the final result.
Here is the main class:
class infixTopostfix
{
public infixTopostfix(string strTemp)
{
strInput = strTemp;
}
private int isOperand(char chrTemp)
{
char[] op = new char[6] { '*', '/', '+', '-', '^', '(' };
foreach (char chr in op)
if (chr == chrTemp)
{
return 1;
}
return 0;
}
private int isOperator(char chrTemp)
{
char[] op = new char[5] { '*', '/', '+', '-', '^' };
foreach (char chr in op)
if (chr == chrTemp)
{
return 1;
}
return 0;
}
private string strResualt = null;
private string strInput = null;
public string createPrifex()
{
int intCheck = 0;
//int intStackCount = 0;
object objStck = null;
for (int intNextToken = 0; intNextToken <= strInput.Length - 1; intNextToken++)
{
intCheck = isOperand(strInput[intNextToken]);
if (intCheck == 1)
stkOperatore.Push(strInput[intNextToken]);
else
if (strInput[intNextToken] == ')')
{
int c = stkOperatore.Count;
for (int intStackCount = 0; intStackCount <= c - 1; intStackCount++)
{
objStck = stkOperatore.Pop();
intCheck = isOperator(char.Parse(objStck.ToString()));
if (intCheck == 1)
{
strResualt += objStck.ToString();
}
}
}
else
strResualt += strInput[intNextToken];
}//end of for(int intNextToken...)
int intCount = stkOperatore.Count;
if (intCount > 0)
{
int c = stkOperatore.Count;
for (int intStackCount = 0; intStackCount <= c - 1; intStackCount++)
{
objStck = stkOperatore.Pop();
intCheck = isOperator(char.Parse(objStck.ToString()));
if (intCheck == 1)
{
strResualt += Convert.ToString(objStck);
}
}
}
return strResualt;
}
private System.Collections.Stack stkOperatore = new System.Collections.Stack();
}
}
Here is the input that fails:
A^B^(C-D/(E+F))-(G+H)^L*Z+Y
the result of this code which is incorrect:
ABCDEF+/-^^GH+-LZY+*^
The correct result:
ABCDEF+/-^^GH+L^Z*-Y+