Search
 
SCRIPT & CODE EXAMPLE
 

JAVA

string expression execution for java

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();
}
Comment

PREVIOUS NEXT
Code Example
Java :: java singleton with synchronized double check 
Java :: In similar fashion we will use (RIGHT – SHIFT) to retrieve bits from val 6 at a time 
Java :: how to reinstall nginuity 
Java :: Java Maven Using platform encoding (UTF-8 actually) to read mojo metadata, i.e. build is platform dependent! 
Java :: java 11 read file line by line 
Java :: UserRedirectRequiredException: A redirect is required to get the users approval spring boot 5 security 
Java :: hadoop fs get size of directory java 
Java :: JavaFX font display issue 
Java :: Java Documenting assumptions 
Java :: make form items vertica 
Java :: conditional statement problems in java 
Java :: grunt registertask multiple 
Java :: using handler runnable for refresh android 
Java :: java convert string with commas to long 
Java :: JUnit5 @Test method whose data comes from dataForTestSearchString 
Java :: create generator hibernate 
Java :: java @documented 
Java :: least count of words required to construct a target string 
Java :: check java variable type using getSimpleName method 
Java :: primefaces p:dataexporter encoding for pdf 
Java :: turn array to image java 
Java :: minecraft bukkit coding player sharing variable 
Java :: exit for loop java stack overflow 
Java :: jsonpath xpath java 
Java :: java random.nextint 
Java :: java mockito print called methods 
Java :: print string in reverse order using recursion java 
Java :: is overriding only works with inherited methods? 
Java :: java Prefix Sum of Matrix (Or 2D Array) 
Java :: javafx character counter 
ADD CONTENT
Topic
Content
Source link
Name
3+8 =