I am learning to use android studio to make an app, so I am making a simple calculator, but I have run into a problem getting the correct answer

Coleman :

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;
}
Robo Mop :

.charAt() returns a character, not an integer. For example, "8*8" has 3 characters - '8', '*', and '8'. When you perform a mathematical operation with a character, it uses the ASCII value of the character eg: 'A' has an ASCII value of 65. '0' has a value of 48.

Thus, '1' + '2' = 49 + 50 = 99

You need to convert the String part before the '*' into a number, right? Java has an easy solution for that: the Double.parseDouble() method:

String text = "567";
int number = Double.parseDouble(text);

To solve your particular question, you should try this:

int x = s.indexOf('*');
mult = Double.parseDouble(s.substring(0, x)) * Double.parseDouble(s.substring(x+1));

The best part of this solution is that you can use numbers which have more than one digit, because the code takes everything before and after '*' in s, and converts them to numbers.

Edit: As u/markspace has mentioned in the comment below, you should consider using the in-built parsing library in Java, as seen here: Algebra equation parser for java

Edit 2: I had recommended using Integer.parseInt() to convert the string into a number, but as u/MartinZeitler has pointed out in the comment below, converting to a double value using Double.parseDouble() would be better.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=17083&siteId=1