I am trying to write a method that converts infix to prefix and to do that i want to read a sting reverse and use a stack. When i execute this code i am getting an exception at character = expression.charAt(limit);
how can i fix that code?
My input was 1+3 and the error i got was:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 3 at java.lang.String.charAt(Unknown Source) at PrefixTranslator.translate(PrefixTranslator.java:27) at PrefixTranslatorTest.main(PrefixTranslatorTest.java:11)
PrefixTranslator Class:
public class PrefixTranslator
{
static private String expression;
private MyStack<Character> stack = new MyStack<Character>();
//Constructor
public PrefixTranslator(String infixExpression)
{
expression = infixExpression;
}//End of constructor
public String translate()
{
//Declare Method Variables
String input = "";
String output = "";
char character = ' ';
char nextCharacter = ' ';
for(int limit = expression.length(); limit > 0 ; limit--)
{
character = expression.charAt(limit);
if(isOperator(character))
{
output = output + character + " ";
}
else if(character == '(')
{
stack.push(character);
}
else if(character == ')')
{
while(!stack.top().equals('('))
output = output + stack.pop() + " ";
stack.pop();
}
else
{
if(Character.isDigit(character) && (limit + 1) < limit && Character.isDigit(expression.charAt(limit+1)))
{
stack.push(character);
stack.push(expression.charAt(limit+1));
}
else if(Character.isDigit(character))
{
stack.push(character);
}
else
{
output = output + character;
}
}
}//End of for
while(!stack.isEmpty())
{
output = output + stack.pop() + " ";
}
return output;
}//End of translate method
//Check priority on characters
public static int precedence(char operator)
{
if(operator == '+' || operator =='-')
return 1;
else if(operator == '*' || operator == '/')
return 2;
else
return 0;
}//End of priority method
public boolean isOperator(char element)
{
if(element == '*' || element == '-' || element == '/' || element == '+')
return true;
else
return false;
}//End of isOperator method
}//End of class
PrefixTranslatorTest Class:
import java.util.Scanner;
public class PrefixTranslatorTest{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Enter the expression that you want to convert to prefix.");
String expression = input.next();
PrefixTranslator translator = new PrefixTranslator(expression);
System.out.println(translator.translate());
}
}
For the given input 1+3
expression.length()
returns 3
and you can refer to indexes 0-2
of that string. So, your loop shouldn't be:
for(int limit = expression.length(); limit > 0 ; limit--)
And it should be
for(int limit = expression.length() - 1; limit >= 0 ; limit--)