2

I try to build a calculator with user input and want to calculate everything with Operands in Order. I saved the user input in two String ArrayLists: -> postNumbers for all numbers -> postOperands for all operands

I tried to calculate them with different for loops and switch/cases but it didnt worked right as soon as two pluses or slashes were inputed. Is there a way to put the two ArrayLists into one alternativly and calcute it then like:

List N: 10 5 3 2

List M: 10+5*3-2

List O:   + * -

And then finally put it into a variable?

2 Answers2

1

First, I believe you mean postOperators, as opposed to postOperands.
An operand is the value.

You can create a for-loop to iterate the List of numbers, and compile them into a result.

Additionally, you should review the Abstract Syntax Tree structure.

/** @param postNumbers must be mutable */
double evaluate(List<String> postNumbers, List<String> postOperators) {
    double result = Double.parseDouble(postNumbers.remove(0));
    double value;
    char operator;
    for (int index = 0; index < postNumbers.size(); index++) {
        value = Double.parseDouble(postNumbers.get(index));
        operator = postOperators.get(index).charAt(0);
        result = switch (operator) {
            case '*' -> result * value;
            case '/' -> result / value;
            case '+' -> result + value;
            case '-' -> result - value;
            default -> throw new IllegalArgumentException();
        };
    }
    return result;
}

Example input

List<String> postNumbers = new ArrayList<>(Arrays.asList("10", "5", "3", "2"));
List<String> postOperators = List.of("+", "*", "-");
double result = evaluate(postNumbers, postOperators);

Output

43.0
Reilas
  • 3,297
  • 2
  • 4
  • 17
-2

Here is an answer to your question:

import java.util.*;
public class Calculator {
    public static void main(String[] args) {
        List<Double> numbers = Arrays.asList(10.0, 5.0, 3.0, 2.0);
        List<Character> operands = Arrays.asList('+', '*', '-');

        Stack<Double> stack = new Stack<>();
        int operandIndex = 0;

        for (Double number : numbers) {
            stack.push(number);

            if (operandIndex < operands.size()) {
                char operand = operands.get(operandIndex);
                double result = 0;

                switch (operand) {
                    case '+':
                        result = stack.pop() + stack.pop();
                        break;
                    case '-':
                        result = -stack.pop() + stack.pop();
                        break;
                    case '*':
                        result = stack.pop() * stack.pop();
                        break;
                    case '/':
                        result = 1 / stack.pop() * stack.pop();
                        break;
                }

                stack.push(result);
                operandIndex++;
            }
        }

        System.out.println(stack.pop());
    }
}
Sina Salmani
  • 89
  • 1
  • 9
  • You don't need to use a stack for this simple operation, since the author don't need or requested operator precedence. The java.util.Stack class should be avoided in non sinchronized algorithms and/or envinronments since it extends Vector that has synchronized operations. A better option is a Deque as a type and ArrayDeque as implementation if you really need a stack. – davidbuzatto May 24 '23 at 15:23
  • This doesn't run, I get `Exception in thread "main" java.util.EmptyStackException`. – Reilas May 24 '23 at 15:38