简体   繁体   中英

Stack and operators

Im trying to calculate easy expressions with stack. See my code and please tell me how to solve it.

The way i want it: pop the next operator in the stack and then find the result of "x operator y". The result should be 5. I guess i must convert to integers or something.

import java.util.*;
public class testfil {

   public static void main(String[] args) {
     Stack<String> stack = new Stack<String>();
     stack.push("+");

     String x="2";
     String y="3";

      int result =   (Integer.valueOf(x), Integer.valueOf(stack.pop()), Integer.valueOf(y));


    System.out.print(result);
  }
}

You can use strategy pattern:

public enum Operators {
    SUM {
        public int perform(int a, int b) {
            return a + b;
        }
    },
    MULTIPLY {
        public int perform(int a, int b) {
            return a * b;
        }
    },
    ...

    public abstract int perform(int a, int b);
}

then you would use it like:

stack.pop().perform(c, stack.pop().perform(a, b));

Instead of trying to use binary operators in this way, because it won't work. This is even more true of strings that look like binary operators.

Instead, you need to implement your logic as functions.

For example, an Add function...

public class Add implements BiFunction<Integer, Integer, Integer> {
    public Integer apply(Integer a, Integer b) {
        return a + b;
    }
}

Your code will then look like this

Stack<BiFunction> stack = new Stack<BiFunction>();
stack.push(new AddFunction());

 Integer x=2;
 Integer y=3;

 int result = stack.pop().apply(x, y);

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