Reputation: 17
i have created a scientific calculator as android application. i am having problem when calculating the veriables. my question is that you saw in many scientific calculators if user input a data like this 45+54*2 the calculator calculate multiply first and than do addition and subtraction. but my calculator is just adding 45 with 54 and than multiplying 2 with the result. how can i fix this issue. please check the code below for understand my problem.
List<Double> numbers = new ArrayList<>();
List<Character> operators = new ArrayList<>();
/*the above two are arraylists which input data from user*/
..............
/*when user press = button the below code runs*/
void result() {
numbers.add(currentnum);
if (checketfield == 0) {
et1.setText(currentcalc.getText());
} else {
et1.setText("");
}
for (int i = 0; i < handler; i++) {
switch (operators.get(i)) {
case '+':
if (i < 1) {
total3 = numbers.get(i);
}
total3 += numbers.get(i + 1);
break;
case '-':
if (i < 1) {
total3 = numbers.get(i);
}
total3 -= numbers.get(i + 1);
break;
case '*':
if (i < 1) {
total3 = numbers.get(i);
}
total3 *= numbers.get(i + 1);
break;
case '/':
if (i < 1) {
total3 = numbers.get(i);
}
total3 /= numbers.get(i + 1);
break;
}
et1.setText(Double.toString(total3));
}
}
Upvotes: 0
Views: 219
Reputation: 26
Create a while loop, with the condition being that there are still entries in the operators ArrayList. Then, inside that while loop, put the for loop, but split it up into two for loops. The first for looks for multiplication and division. The second for looks for addition and subtraction. This will ensure you keep the order of operations. Each time an operator is matched and evaluated, remove it from the ArrayList.
Upvotes: 1