Hi there, I was curious why I am getting an out of bounds exception in this code. Any pointers would be very helpful. Thanks daniel
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
/*
Data Structures Infix2Postfix:
Ex. 23.6, pp. 1208 OR Ex. 25.6 Page 1363 OR Ex. 26.6 Page 1353 Mar 11
*
* http://www.osix.net/modules/article/?id=786
*
* */
public class Infix2Postfix
{
private Stack<String> stack;
private String infixExp;
private String postfixExp = "";
public Infix2Postfix(string exp)
{
String str = "";
infixExp = exp.Trim();
stack = new Stack<String>();
for (int i = 0; i < infixExp.Length; i++)
{
str = infixExp.Substring(i, i + 1); //error on this line
Match match = Regex.Match(str, "[a-zA-Z]|\\d");
if (match.Success)
{
postfixExp += str;
}
else if (isOperator(str))
{
if (stack.Count == 0)
{
stack.Push(str);
}
else
{
String stackTop = stack.Peek();
while (Precedence(stackTop, str).Equals(stackTop) && !(stack.Count == 0))
{
postfixExp += stack.Pop();
if (!(stack.Count == 0))
{
stackTop = stack.Peek();
}
}
stack.Push(str);
}
}
}
while (!(stack.Count == 0))
{
postfixExp += stack.Pop();
}
Console.WriteLine("The postfix form of the expression you entered is: " + postfixExp);
}
private bool isOperator(String ch)
{
String operators = "*/%+-^";
if (operators.IndexOf(ch) != -1)
return true;
else
return false;
}
private String Precedence(String op1, String op2)
{
String multiplicativeOps = "*/%^";
String additiveOps = "+-";
if ((multiplicativeOps.IndexOf(op1) != -1) && (additiveOps.IndexOf(op2) != -1))
return op1;
else if ((multiplicativeOps.IndexOf(op2) != -1) && (additiveOps.IndexOf(op1) != -1))
return op2;
else if ((multiplicativeOps.IndexOf(op1) != -1) && (multiplicativeOps.IndexOf(op2) != -1))
return op1;
else
return op1;
}
}
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
char doAgain = 'Y';
do
{
Console.WriteLine("Please enter an expression:");
String expression = Console.ReadLine();
Infix2Postfix i = new Infix2Postfix(expression);
Console.WriteLine("Would you like to run the program again (Y) or (N):");
String doAgainString = Console.ReadLine().Trim().ToUpper();
while (doAgainString.ToUpper() != "Y" && doAgainString.ToUpper() != "N")
{
Console.WriteLine("Invaled!Input please enter either \"Y\" or \"N\"");
doAgainString = Console.ReadLine().Trim().ToUpper();
}
doAgain = doAgainString[0];
} while (doAgain == 'Y');
}
}
}