简体   繁体   中英

Stack problem java. Postfix Evaluation

Hey Guys I'm having a problem when I run my program. In the PostfixEvaluate() Method is where it takes in a string and solves the postfix problem and returns it. Well when I go to run it, I'm getting a bunch of random numbers(some repeated), I'm going crazy because I don't know what else to try and I've spent more time on this than it should normally take.

Heres the PostfixEvaluate Method:

   public int PostfixEvaluate(String e){
        //String Operator = "";
    int number1;
        int number2;
        int result=0;
        char c;
        //number1 = 0;
        //number2 = 0;

        for(int j = 0; j < e.length(); j++){
            c = e.charAt(j);
            if (c != '+'&& c!= '*' && c!= '-' && c!= '/') {
                //if (c == Integer.parseInt(e)) {   
                s.push(c); 
        }
            else {
                number1 = s.pop();
                number2 = s.pop();
                switch(c) {
                    case '+':
                    result = number1 + number2;
                    break;
                    case '-':
                    result = number1 - number2;
                    break;
                    case '*':
                    result = number1 * number2;
                    break;
                    case '/':
                    result = number1 / number2;
                    break;
                    } s.push(result);
                }
            System.out.println(result);
        } 
            return s.pop();
}

public static void main(String[] args) {
    Stacked st = new Stacked(100);
    String y = new String("(z * j)/(b * 8) ^2");
    String x = new String("2 3 + 9 *");
    TestingClass clas = new TestingClass(st);

    clas.test(y);


    clas.PostfixEvaluate(x);




 }
        }

This is the Stack Class:

 public class Stacked  {

    int top;
    char stack[];
    int maxLen;

    public Stacked(int max) {
        top = -1; 
        maxLen = max; 
        stack = new char[maxLen];

        }

    public void push(int result) {
            top++;
            stack[top] = (char)result;

        }

    public int pop() {
        int x;
        x = stack[top];
        //top = top - 1;
        top--;

        return x;

    }

    public boolean isStackEmpty() {
            if(top == -1) {
                System.out.println("Stack is empty " + "Equation Good");

                return true;
            } 
            else 
                System.out.println("Equation is No good");
                return false;
    }

    public void reset() {

        top = -1;
    }

    public void showStack() {
        System.out.println(" ");
        System.out.println("Stack Contents...");
        for(int j = top; j > -1; j--){
            System.out.println(stack[j]);
        }
        System.out.println(" ");
    }

    public void showStack0toTop() {
        System.out.println(" ");
        System.out.println("Stack Contents...");
        for(int j=0; j>=top; j++){
            System.out.println(stack[j]); 
        }
        System.out.println(" ");
        }
    }

It looks to me like you aren't handling spaces at all.

This means that when you put in a space, it is implicitly converting the character space to the ascii value of it (32) when it pops it off the stack during an operation. Also, it looks like you are assuming that all numbers/results will be single digit, and casting from char to int, which is not what you want to do, since that will convert the char to the ascii value of the char, ' ' -> 32, '3' -> 51, etc.

If I were you, I would do this for your loop in PostfixEvaluate:

while(!e.equals("")){
    string c;
    int space = e.indexOf(' ');
    if(space!=-1){
        c = e.substring(0,space);
        e = e.substring(space+2);
    } else{
        c = e;
        e = "";
    }
    if (!c.equals("+")&& !c.equal("*") && !c.equals("-") && !c.equals("/")) {
    //...
}

and change your stack to hold strings or ints.

The problem is that you are pushing char onto a stack as an int , so you are unintentionally working with the ascii representations of numbers, which is not the actual value of the number.

Instead of this complicated character walking, tokenize the input string using String.split() . Example:

String[] tokens = e.split(" ");
for(String token:tokens){
    if (!"+".equals(token) && !"*".equals(token) && !"-".equals(token) && !"/".equals(token)) {
        s.push(Integer.parseInt(token)); 
    } else {
        ....
    }
}

You need to split the string into tokens first:

/* Splits the expression up into several Strings,
 * all of which are either a number or and operator,
 * none of which have spaces in them. */
String [] expressionAsTokens = e.split(" ");

Then you need to make sure you compare Strings, not chars:

//compare strings instead of chars
String token = expressionAsTokens[j];
if (!"+".equals(token) && !"*".equals(token) && !"-".equals(token) && !"/".equals(token)) {
    s.push(Integer.parseInt(token)); 
} else {
    //same code as you had before
}

Also, is there any reason you are storing everything as a char array in your Stacked class? Your pop() method returns and integer, yet everything is stored as a char .

For this application, everything should be stored as an integer:

public class Stacked {
    int stack[]; // array is of type integer
    int top;
    int maxLen;

    // constructor

    public void push() {/*...*/}
    public int pop() {/*...*/} //pop returns an int as before

    //...
}

One final note: Be careful what order you add and subtract the numbers in. I don't remember if postfix operands are evaluated left first or right first, but make sure you get them in the right order. As you have it now, 2 3 - 4 * would evaluate as 4 * (3 - 2) and I think it should be (2 - 3) * 4 . This won't matter with adding and multiplying, but it will with subtracting and dividing.

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