I worked on a simple calculator app that does not pile up an expression like google calculator. Instead it stores the result in an operand when an operation button is pressed and so it does not follow BODMAS precedence rules. Like if I perform 2 + 2 / 2 I get 4 as the result whereas the result should be 3 as the division is performed first Is there a way to take input as a whole expression and then evaluate it collectively? Are there any predefined classes that I can use that are included in java?
The code for the onClickListeners of operators and calculation performing function is:
View.OnClickListener opListener = new View.OnClickListener() {
@Override
public void onClick(View view) {
Button b = (Button) view;
String op = b.getText().toString();
String value = newNumber.getText().toString();
try {
Double doubleValue = Double.valueOf(value);
performOperation(doubleValue, op);
} catch (NumberFormatException e) {
newNumber.setText("");
}
pendingOperation = op;
displayOperation.setText(pendingOperation);
}
};
private void performOperation(Double value, String operation) {
if (operand1 == null) {
operand1 = value;
} else {
if (pendingOperation.equals("=")) {
pendingOperation = operation;
}
switch (pendingOperation) {
case "=":
operand1 = value;
break;
case "/":
if (value == 0) {
operand1 = 0.0;
Toast.makeText(this,"Cannot Divide By Zero, Resetting value to zero",Toast.LENGTH_LONG).show();
} else {
operand1 /= value;
}
break;
case "*":
operand1 *= value;
break;
case "+":
operand1 += value;
break;
case "-":
operand1 -= value;
break;
}
}
result.setText(operand1.toString());
newNumber.setText("");
}