0

I'm building this calculator app with two textviews (one for the formula and one for the result). Now the result after calculations is stored in a variable called result which is left empty by default. But when I run it, after the function executes, everything works but the result variable still remains an empty string. Please help me.

ScientificCalculator.java

 int prevAnswer = 0;
TextView formulascreen;
TextView resultscreen;
String formuladisplay = "";
String resultdisplay = "";
String result = "";
String operator;

public void onClickEquals(View view) {

    Toast toast = Toast.makeText(getContext(), "Equals to: " + String.valueOf(result), Toast.LENGTH_SHORT);
    toast.show();

    if (operator == "+" || operator == "-" || operator == "x" || operator == "÷") {

        getResult();
        updateresultdisplay();

    }

}

private boolean getResult() {

    if (operator == "") return false;

    String[] operation = formuladisplay.split(Pattern.quote(operator));

    if (operation.length < 2) return false;

    result = String.valueOf(res.format(simpleOp(operation[0], operation[1], operator)));

    return true;

}

public double simpleOp(String a, String b, String op) {

    switch (op) {

        case "+":
            return Double.valueOf(a) + Double.valueOf(b);

        case "-":
            return Double.valueOf(a) - Double.valueOf(b);

        case "x":
            return Double.valueOf(a) * Double.valueOf(b);

        case "÷":
            return Double.valueOf(a) / Double.valueOf(b);

        default:
            return -1;

    }

}
Dayem Saeed
  • 325
  • 5
  • 15

1 Answers1

1

You have two result variables: result and resultdisplay. The calculation code updates result, but within updateresultdisplay() you use display the contents of the (unchanging) resultdisplay.

So you just need to update updateresultdisplay() to

private void updateresultdisplay() {
    resultscreen.setText(result);
}
Thomas Kläger
  • 17,754
  • 3
  • 23
  • 34
  • Thanks for the advice but I tried it and its returning result as an empty string again :(. – Dayem Saeed Jun 01 '16 at 20:13
  • Apparently, I found out that the "if" function in the onClickEquals() method doesn't run. – Dayem Saeed Jun 01 '16 at 20:16
  • Where should onClickEquals() be triggered from? Can you post all the code? – Mobile Developer Jun 01 '16 at 20:23
  • No need. Fixed it. Just had to remove the stupid "if" statement and also made the change suggested by Thomas Kläger. :). Thanks for the help :) – Dayem Saeed Jun 01 '16 at 20:26
  • @DayemSaeed in `onClickEquals` you are comparing `operator == "+"`, which is a comparison for the same string object. You should compare strings with the `equals(..)` method: `operator.equals("+")`, which compares for the same content (see http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) – Thomas Kläger Jun 01 '16 at 20:45