I wrote the following method to convert an infix expression to a postfix expression. If the commented code is removed, the program will return a valid expression given single digit integers; 11 + 2 will result in 1 1 2 + rather than 11 2 +, but 1 + 2 - 3 returns 1 2 + 3 -. In order to include n-digit numbers, I implemented an if-statement which concatenate a space to postfix string if the adjacent character is NOT a number. However, during execution the following error is produced:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 3
Code:
public static String postfixConversion(String input) {
int i;
String postfix = "";
Stack<Character> stack = new Stack<Character>();
for (i = 0; i < input.length(); i++) {
while (input.charAt(i) == ' ') {
++i;
}
if (Character.isDigit(input.charAt(i))) {
postfix += input.charAt(i);
if (!Character.isDigit(input.charAt(i+1))) { //EXCEPTION OCCURS
postfix += ' ';
}
}
else if (precedenceLevel(input.charAt(i)) != 0) {
while ((!stack.isEmpty()) && (precedenceLevel(stack.peek()) >= precedenceLevel(input.charAt(i))) && (stack.peek() != '(')) {
postfix += stack.peek();
postfix += ' ';
stack.pop();
}
stack.push(input.charAt(i));
}
else if (input.charAt(i) == '(') {
stack.push(input.charAt(i));
}
else if (input.charAt(i) == ')') {
while (!stack.isEmpty() && stack.peek() != '(') {
postfix += stack.peek();
stack.pop();
}
stack.pop();
}
}
while (!stack.isEmpty()) {
postfix += stack.peek();
postfix += ' ';
}
return postfix;
}
Any assistance would be appreciated :)
Aucun commentaire:
Enregistrer un commentaire