0
votes

So I'm currently working on a homework assignment that is using a Stack for Postfix and Infix expressions. My question is, how would I setup my stack so that I can push and pop chars and doubles. Right now I'm able to get the Infix to Postfix to work properly, but when I try to calculate the total for the postfix it bombs. Right now I'm using an array that will store the values of the letters, A-Z. This is my postFix eval function.

public double postFix(String infix, double[] numbers) throws Exception{
    Stack myStack=new Stack();
    for(int i=0; i<infix.length(); i++){
        char ch=infix.charAt(i);
        if(ch=='+'){
            char one=(char) myStack.pop();
            char two=(char) myStack.pop();

            double first=numbers[one-65], second=numbers[two-65];
            double temp=first+second;
            myStack.push((char) temp);
        }
        else if(ch=='-'){
            char one=(char) myStack.pop();
            char two=(char) myStack.pop();

            double first=numbers[one-65], second=numbers[two-65];
            double temp=first-second;
            myStack.push((char) temp);              
        }
        else if(ch=='*'){
            char one=(char) myStack.pop();
            char two=(char) myStack.pop();

            double first=numbers[one-65], second=numbers[two-65];
            double temp=first*second;
            myStack.push((char) temp);              
        }
        else if(ch=='/'){
            char one=(char) myStack.pop();
            char two=(char) myStack.pop();

            double first=numbers[one-65], second=numbers[two-65];
            double temp=first/second;
            myStack.push((char) temp);              
        }
        else if(ch=='^'){
            char one=(char) myStack.pop();
            char two=(char) myStack.pop();

            double first=numbers[one-65], second=numbers[two-65];
            double temp=Math.pow(first, second);
            myStack.push((char) temp);              
        }
        else{
            myStack.push(ch);
        }
    }
    return myStack.pop();

This is my Node class

private class Node{
    protected char data;
    protected Node next;

    private Node(){
        this.data=(Character) null;
        this.next=null;
    }

    private Node(char data, Node next){
        this.data=data;
        this.next=next;
    }
}

If there is anything else that you need from me please don't hesitate to ask

Should I create two stacks for this?

1

1 Answers

0
votes

Here's how I would do it...

I would make the stack nodes be able to hold either char or double data values. (Note that these will actually be the boxed types Character and Double.)

The node class would then have a getValue() method that returns the value, appropriately converted into a double type. This will ensure that the arithmetic operations work correctly.