2

This is my class:

import java.io.*;
import java.util.*;
import java.lang.*;
import java.util.Scanner;
import java.util.List;
import java.util.Stack;

/**
 *
 * @author rtibbetts268
 */
public class InfixToPostfix
{
        /**
         * Operators in reverse order of precedence.
         */
    private static final String operators = "_-+/*";
    private static final String operands = "0123456789x";

    public String xToValue(String postfixExpr, String x)
    {
        char[] chars = postfixExpr.toCharArray();
        StringBuilder newPostfixExpr = new StringBuilder();

        for (char c : chars)
        {
            if (c == 'x')
            {
                newPostfixExpr.append(x);
            }
            else
            {
                newPostfixExpr.append(c);
            }
        }
        return newPostfixExpr.toString();
    }

    public String convert2Postfix(String infixExpr)
    {
        char[] chars = infixExpr.toCharArray();
        StringBuilder in = new StringBuilder(infixExpr.length());

        for (int i : chars)
        {
            if (infixExpr.charAt(i) == '-')
            {
                if (isOperand(infixExpr.charAt(i+1)))
                {
                    if (i != infixExpr.length())
                    {
                        if (isOperator(infixExpr.charAt(i-1)))
                            in.append('_');
                    }
                    else
                    {
                        in.append(infixExpr.charAt(i));
                    }
                }
                else
                {
                   in.append(infixExpr.charAt(i));
                }
            }
            else
            {
                in.append(infixExpr.charAt(i));
            }
        }

        chars = in.toString().toCharArray();
        Stack<Character> stack = new Stack<Character>();
        StringBuilder out = new StringBuilder(in.toString().length());

        for (char c : chars)
        {
            if (isOperator(c))
            {
                while (!stack.isEmpty() && stack.peek() != '(')
                {
                    if (operatorGreaterOrEqual(stack.peek(), c))
                    {
                        out.append(stack.pop());
                    }
                    else
                    {
                        break;
                    }
                }
                stack.push(c);
            }
            else if (c == '(')
            {
                stack.push(c);
            }
            else if (c == ')')
            {
                while (!stack.isEmpty() && stack.peek() != '(')
                {
                    out.append(stack.pop());
                }
                if (!stack.isEmpty())
                {
                    stack.pop();
                }
            }
            else if (isOperand(c))
            {
                out.append(c);
            }
        }
        while (!stack.empty())
        {
            out.append(stack.pop());
        }
        return out.toString();
    }

    public int evaluatePostfix(String postfixExpr)
    {
        char[] chars = postfixExpr.toCharArray();
        Stack<Integer> stack = new Stack<Integer>();
        for (char c : chars)
        {
            if (isOperand(c))
            {
                stack.push(c - '0'); // convert char to int val
            }
            else if (isOperator(c))
            {
                int op1 = stack.pop();
                int op2 = stack.pop();
                int result;
                switch (c) {
                    case '*':
                        result = op1 * op2;
                        stack.push(result);
                        break;
                    case '/':
                        result = op2 / op1;
                        stack.push(result);
                        break;
                    case '+':
                        result = op1 + op2;
                        stack.push(result);
                        break;
                    case '-':
                        result = op2 - op1;
                        stack.push(result);
                        break;
                }
            }
        }
        return stack.pop();
    }

    private int getPrecedence(char operator)
    {
        int ret = 0;
        if (operator == '_')
        {
            ret = 0;
        }
        if (operator == '-' || operator == '+')
        {
            ret = 1;
        }
        else if (operator == '*' || operator == '/')
        {
            ret = 2;
        }
        return ret;
    }

    private boolean operatorGreaterOrEqual(char op1, char op2)
    {
        return getPrecedence(op1) >= getPrecedence(op2);
    }

    private boolean isOperator(char val)
    {
        return operators.indexOf(val) >= 0;
    }

    private boolean isOperand(char val)
    {
        return operands.indexOf(val) >= 0;
    }

}

In it I change infix expressions to postfix expressions with the method convert2Postfix()

There is a small section in it at the very beginning where I am rewriting the string input with all negative numbers having a '_' infront of them instead of a "-". It doesn't work.

ex: change -4 to _4

What do I need to do to make this work?

Jens Erat
  • 37,523
  • 16
  • 80
  • 96
Ryan Tibbetts
  • 412
  • 1
  • 8
  • 22
  • 1
    Please isolate your problem into small compilable code. Post this reduced code, results your getting, and results you belive you should be getting instead. – PM 77-1 Apr 10 '13 at 07:19
  • @PM 77-1 All the code here works cohesively. I cannot show you the method in question without showing you all of the code. – Ryan Tibbetts Apr 10 '13 at 23:33

1 Answers1

2

You have a number of errors here, here is the first one:

 for (int i : chars)

chars is converted to the corresponding int. For example if chars contains one single character 'A':

  char [] chars = new char[1];
    chars[0] = 'A';
    for(int i: chars){
        System.out.println(i); //You will have a '65' here
    }

What you really mean is probably:

 for (int i=0;i<chars.length;++i)

This is also wrong:

  if (isOperator(infixExpr.charAt(i-1)))

It should be :

  if (isOperator(infixExpr.charAt(i)))

Then there is a problem in the way you put and remove elements in the stack. After all this changes you should also do this:

 return out.reverse().toString();

instead of :

 return out.toString();

Here is what I ended up with: http://pastebin.com/2TLqPUsH (Change the name of the classes of course)

Eugene
  • 117,005
  • 15
  • 201
  • 306
  • Thank you for your input. You effectively answered my question, I will up vote this. However everything else you have does not function correctly with my code and I wanted to point this out. I'm making a postfix expression, not a prefix one. Also if you read my code more in depth you will notice I have another method that computes and does the math. I have yet to set it up to work with negatives, but with all positive integers it will do the moth of the postfix equation w.o me having to reverse anything or what not. – Ryan Tibbetts Apr 10 '13 at 23:31