简体   繁体   中英

Convert Infix expression to prefix and postfix expression with Java

I want to make an application to convert expression from infix mode to postfix and prefix mode.

For example:

infix : a+b*c

postfix: abc*+

prefix : +a*bc

I want this by two classes, a class for postfix convert and an other class for prefix convert.

In addition I have written a class for stack like this :

public class Stack {

int top = 0;
int stackSize = 0;
String[] stack;

public Stack(int stackSize){
    this.stackSize = stackSize;
    stack = new String[stackSize];
}

public int getTop(){
    return top;
}

public void push(String arg)throws Exception{
    if(top == stackSize){
        throw new Exception("Stack is full!");
    }
    else{
        this.stack[top++] = arg;
    }
}

public String pop()throws Exception{
    if(top == 0){
        throw new Exception("Stack is empty");
    }
    else{
        return this.stack[--top];
    }
}

public int stackCount(){
    return top++;
}
}

I tried this code as postfix class :

public class Postfix {
Stack stack = new Stack(1000);
char []operators = {'(','*','%','/','+','-',')'}; 
char[] infixExpression;
public Postfix(String infixExpression){
    this.infixExpression = infixExpression.toCharArray();
}

int priority(char operator){
    int result = 0;
    switch(operator){
    case '(':
        result = 1;
        break;
    case '*':
        result = 2;
        break;
    case '%':
        result = 3;
        break;
    case '/':
        result = 4;
        break;
    case '+':
        result = 5;
        break;
    case '-':
        result = 5;
        break;
    case ')':
        result = 7;
    }
    return result;
}

public String convertToPostfix(){
    int priority;
    String lastData;
    String exp = "";
    for(int i = 0;i<this.infixExpression.length;i++){
        priority = priority(this.infixExpression[i]);
        if(priority == 0){
            exp += this.infixExpression[i];
        }
        else if(priority == 1){
            try {
                stack.push(String.valueOf(this.infixExpression[i]));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        else if(priority == 7){
            while(stack.top != 0){
                try {
                    lastData = stack.pop();
                    if(!lastData.equals("(")){
                        exp += lastData;
                    }
                    else{
                        break;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        else{
            try { 
                if(stack.top != 0){
                    while(true){
                        lastData = stack.pop();
                        stack.push(lastData);
                        if(stack.top == 0 || lastData.equals("(") || priority(lastData.toCharArray()[0]) > priority){
                            stack.push(String.valueOf(this.infixExpression[i]));
                            break;
                        }
                        exp += stack.pop();
                    }
                }else{
                    stack.push(String.valueOf(this.infixExpression[i]));
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    if(stack.top != 0){
        try {
            while(stack.top != 0){
                exp += stack.pop();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return exp;
}
}

but this doesn't work with Parenthesis.

All you need is:

  1. Split input expression to items, split items to multipliers.
  2. Add to buffer parts and delimiters in the order you need

Some bad code to do it:

public class Converter {

    private String infix;

    private void addMultPre(StringBuilder builder, String item) {
        String[] multipliers = item.split("[*/]");
        for (int j = 0; j < multipliers.length - 1; j++) {
            builder.append(infix.charAt(builder.length() + multipliers[j].length()));
            builder.append(multipliers[j]);
        }
        builder.append(multipliers[multipliers.length - 1]);
    }

    private void addMultPost(StringBuilder builder, String item) {
        String[] multipliers = item.split("[*/]");
        builder.append(multipliers[0]);
        for (int j = 1; j < multipliers.length; j++) {
            builder.append(multipliers[j]);
            builder.append(infix.charAt(builder.length()));
        }
    }

    public String prefix() {
        String[] items = infix.split("[+-]");
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < items.length - 1; i++) {
            builder.append(infix.charAt(builder.length() + items[i].length()));
            addMultPre(builder, items[i]);
        }
        addMultPre(builder, items[items.length - 1]);
        return builder.toString();
    }

    public String postfix() {
        String[] items = infix.split("[+-]");
        StringBuilder builder = new StringBuilder();
        char sign;
        addMultPost(builder, items[0]);
        for (int i = 1; i < items.length; i++) {
            sign = infix.charAt(builder.length());
            addMultPost(builder, items[i]);
            builder.append(sign);
        }
        return builder.toString();
    }

    public Converter(String infix) {
        this.infix = infix;
    }

    public static void main(String[] args) {
        Converter c = new Converter("a+b*c");
        System.out.println(c.postfix());
        System.out.println(c.prefix());
    }
}

Output:

abc*+
+a*bc

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM