I need to perform arithmetic operations using the elements in a list. For example, if I have a list of elements [25, +, 5, -, 8, /, 4] how can I convert this as an arithmetic operation in the form 25+5-(8/4) and print its result (28 in this example)? The list I used is of type String. Anyone, please help me to solve this problem. I am new to Arraylist and all.
Asked
Active
Viewed 470 times
0
-
Arraylist alone won't help you with this, you need an expression builder. I don't understand why you needed this if you are new to ArrayLists though! – Aman Oct 24 '20 at 18:01
1 Answers
0
An expression as List:
List<String> expression = new ArrayList();
Collections.addAll(expression, "25", "+", "5", "-", "8", "/", "4");
Now you have to do operations till there is just one term.
You can do the evaluation as a human: first look at * and /, then at + and -. There are really many variants to write this.
while (expression.size() > 1) {
int terms = expression.size();
// ... reduce expression:
// 1. * and /:
...
if (expression.size() < terms) {
continue;
}
// 2. + and -:
for (int i = 1; i + 1 < experesssion.size(); i += 2) {
String operator = experesssion.get(i);
switch (operator) {
case "+":
int lhs = Integer.parseInt(expression.get(i - 1));
int rhs = Integer.parseInt(expression.get(i + 1));
int n = lhs + rhs;
expression.remove(i);
expression.remove(i +1);
expression.set(i - 1, String.valueOf(n));
i -= 2; // Keep at this operator position.
break;
...
}
}
if (expression.size() == terms) {
System.out.println("Could not reduce expression: " + expression);
break;
}
}
String result = expression.get(0);
System.out.println(result);
Write your own loop(s). The code aboveis not necessarily very logical.

Joop Eggen
- 107,315
- 7
- 83
- 138