Advertisement
dimon2242

Untitled

Aug 31st, 2021 (edited)
1,314
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.97 KB | None | 0 0
  1. import java.util.Arrays;
  2. import java.util.List;
  3. import java.util.Stack;
  4.  
  5. public class Test {
  6.  
  7.     public static void main(String[] args) {
  8.         Stack<String> stack = new Stack<>();
  9.         int result = 0;
  10.         String inputString = "5 7 + 3 - 5 +";
  11.         List<String> operators = Arrays.asList("+", "-");
  12.         String[] params = inputString.split(" ");
  13.         for (String op: params) {
  14.             if (operators.contains(op)) {
  15.                 if (stack.size() == 2) {
  16.                     result += Integer.parseInt(stack.pop());
  17.                 }
  18.  
  19.                 int second = Integer.parseInt(stack.pop());
  20.  
  21.                 if (op.equals("+")) {
  22.                     result += second;
  23.                 }
  24.                 else if(op.equals("-")) {
  25.                     result -= second;
  26.                 }
  27.             }
  28.             else {
  29.                 stack.push(op);
  30.             }
  31.         }
  32.  
  33.         System.out.println("Result: " + result);
  34.     }
  35. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement