Running a math equation in Android

I need to be able to handle a mathematical equation such as "(45 + 9) / 8" in my application. I just wanted to evaluate it using JavaScript, but realized that I can not use javax.script in Android. So, I found WebView, but I have problems using it. Most examples relate to using an external page with JS code or using "javascript: var return ... etc.". I will need to use the latter, but I had problems returning the variable to my application.

Is it possible to use JS eval and then write the value to a hidden TextView?

+7
source share
3 answers

Check out exp4j . This is a simple expression evaluator for java. For the equation that you posted in your question, you can simply do:

Calculable calc = new ExpressionBuilder("(45+9)/8").build() double result1=calc.calculate(); 
+11
source

Try the following:

 import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import javax.swing.JOptionPane; private void btnEqualsActionPerformed(java.awt.event.ActionEvent evt) { String expression = txtResult.getText(); ScriptEngineManager mgr = new ScriptEngineManager(); ScriptEngine engine = mgr.getEngineByName("JavaScript"); try { result = engine.eval(expression).toString(); txtResult.setText(result); } catch (Exception e) { JOptionPane.showMessageDialog(null, txtResult.getText() + " cannot be calculated. Try again!", "Error on calculation!", JOptionPane.WARNING_MESSAGE); txtResult.setText(""); } } 
+1
source

An interesting option for a more advanced expression might be to turn some online calculator into a web service that you can use from your mobile phone.

0
source

All Articles