ztv
ztv

Reputation: 134

Where to enter the string in "evaluate simple math expression"

I'm currently working on a school project in Android. I've written a code which generates a random equation, like 8+4/2, everytime you press a button on the screen and now I want to evaluate the result of the equation which is stored in a String. As there is no simple command to evaluate the result of a simple math expression allready implemented in Android Studio, I found a code here on Stackoverflow.com which evaluates the math expression from a string. (Here is the link to this post: How to evaluate a math expression given in string form? )

Here is the code to evaluate the math expression:

public static double eval(final String str) {
return new Object() {
    int pos = -1, ch;

    void nextChar() {
        ch = (++pos < str.length()) ? str.charAt(pos) : -1;
    }

    boolean eat(int charToEat) {
        while (ch == ' ') nextChar();
        if (ch == charToEat) {
            nextChar();
            return true;
        }
        return false;
    }

    double parse() {
        nextChar();
        double x = parseExpression();
        if (pos < str.length()) throw new RuntimeException("Unexpected: " + (char)ch);
        return x;
    }

    // Grammar:
    // expression = term | expression `+` term | expression `-` term
    // term = factor | term `*` factor | term `/` factor
    // factor = `+` factor | `-` factor | `(` expression `)`
    //        | number | functionName factor | factor `^` factor

    double parseExpression() {
        double x = parseTerm();
        for (;;) {
            if      (eat('+')) x += parseTerm(); // addition
            else if (eat('-')) x -= parseTerm(); // subtraction
            else return x;
        }
    }

    double parseTerm() {
        double x = parseFactor();
        for (;;) {
            if      (eat('*')) x *= parseFactor(); // multiplication
            else if (eat('/')) x /= parseFactor(); // division
            else return x;
        }
    }

    double parseFactor() {
        if (eat('+')) return parseFactor(); // unary plus
        if (eat('-')) return -parseFactor(); // unary minus

        double x;
        int startPos = this.pos;
        if (eat('(')) { // parentheses
            x = parseExpression();
            eat(')');
        } else if ((ch >= '0' && ch <= '9') || ch == '.') { // numbers
            while ((ch >= '0' && ch <= '9') || ch == '.') nextChar();
            x = Double.parseDouble(str.substring(startPos, this.pos));
        } else if (ch >= 'a' && ch <= 'z') { // functions
            while (ch >= 'a' && ch <= 'z') nextChar();
            String func = str.substring(startPos, this.pos);
            x = parseFactor();
            if (func.equals("sqrt")) x = Math.sqrt(x);
            else if (func.equals("sin")) x = Math.sin(Math.toRadians(x));
            else if (func.equals("cos")) x = Math.cos(Math.toRadians(x));
            else if (func.equals("tan")) x = Math.tan(Math.toRadians(x));
            else throw new RuntimeException("Unknown function: " + func);
        } else {
            throw new RuntimeException("Unexpected: " + (char)ch);
        }

        if (eat('^')) x = Math.pow(x, parseFactor()); // exponentiation

        return x;
    }
}.parse();
}

Where in the code above do I have to enter my String with my equation in it? I really don't know where to put it.

Upvotes: 0

Views: 341

Answers (2)

Fedor Tsyganov
Fedor Tsyganov

Reputation: 1002

You can use this method like this

class YourMathClass {
    public static double eval(final String str) { ....
    }
}

And then in your application

 double result = YourMathClass.eval("8+4/2");

or

 String equation = "8+4/2"; //valid equation
 double result = YourMathClass.eval(equation);

if you are using this method inside the class where you need it then use @jenglert's answer

Upvotes: 0

jenglert
jenglert

Reputation: 1609

You need to pass your String to the eval function like this:

String myEquation = "8+4/2";
double answer = eval(myEquation);

Upvotes: 0

Related Questions