I have tried several things to get it to work, but the answers it is returning are very wrong. For example, it returns 1+2 = 99.0 and 1*2 = 2450.0, etc.. All of the buttons work and the main method is fine I think. Below is the way that I am converting the CharSequence in the TextView into a String when the equals button is clicked.
Button btnEquals = (Button)findViewById(R.id.btnEquals);
btnEquals.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String problem = textDisplay.getText().toString();
double intermediate = evalProblem(problem);
String answer = "" + intermediate;
textDisplay.setText(answer);
}
});
And this is the method that I am calling in order to calculate the equation.
public static Double evalProblem(String s) {
double output;
double mult = 0.0;
double add = 0.0;
double sub = 0.0;
double div = 0.0;
if (s.contains("*")) {
int x = s.indexOf("*");
mult = s.charAt(x-1)*s.charAt(x+1);
}
if (s.contains("/")) {
int x = s.indexOf("/");
div = s.charAt(x - 1) / s.charAt(x + 1);
}
if (s.contains("+")) {
int x = s.indexOf(("+"));
add = s.charAt(x-1) + s.charAt(x+1);
}
if (s.contains("-")) {
int x = s.indexOf("-");
sub = s.charAt(x - 1) - s.charAt(x + 1);
}
output = mult + add + sub + div;
return output;
}