3

I am writing a program, and user input ends up as a mathematical expression inside a string. How do I evaluate it into a double?

I don't have a lot of experience in this language, I am mostly familiar with BASIC(lol). So if anyone can give me the simplest step by step instructions to do this, it would be very much appreciated.

base_ten
  • 31
  • 2
  • 4
  • Please give more detail of what you specifically want to do as then it will be easier for people to answer your question. At the moment it is too vague. – haymansfield Oct 09 '13 at 19:41

3 Answers3

1

It is unfortunately not too straightforward in Java. The two top options seem to be using the built-in javascript engine or using the exp4j library.

You can read more about them in these answers: evaluating-a-math-expression-given-in-string-form and java-parse-a-mathematical-expression-given-as-a-string

Community
  • 1
  • 1
alexroussos
  • 2,671
  • 1
  • 25
  • 38
1

You can try this program written in this answer.

https://stackoverflow.com/a/26227947.

I have copy pasted the code here. The explanation of the code is in the original answer if you follow the link.

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();
}`
Harish Anjaneya
  • 133
  • 1
  • 10
0

Ok. I guess you basically have a String like String abc="(56+55(6/655)-5522*1222)"; and you want to evaluate this without changing its type. Yes, there is a library available for this.


Library

Update The Library if there is any update

implementation 'com.udojava:EvalEx:2.7'

----------`

import com.udojava.evalex.Expression;
String memory="";


equal.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            memory=editText.getText().toString();  //Get User's Entered Equation 
            Expression expression=new Expression(memory); //This Library Evaluate It
            String abc=expression.eval().toString(); //Insert The Data into A String
            textView.setText(abc); //Show The Data
        }
    });