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?
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
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments