I'm trying to write a program that will take an input from a user and calculate the total from their input. For example, if the user input "5+30*2" the output would be "65". I've spent hours on this so far and can't seem to get a correct solution. Does anyone have any idea how i would do this?
Asked
Active
Viewed 747 times
-3
-
1Look up the `Scanner` class, it will handle user input. – Justin C Apr 21 '14 at 16:07
-
3i found this question for you http://stackoverflow.com/questions/3422673/evaluating-a-math-expression-given-in-string-form – Marco Acierno Apr 21 '14 at 16:08
-
1Show us what you've tried so far. – Mike B Apr 21 '14 at 16:08
-
This is impossible. It's not possible in Java ;) – Kashif Nazar Apr 21 '14 at 16:15
-
1Where exactly are you stuck? You are having problems with getting the inputs, parsing the equation or displaying the output? – Kashif Nazar Apr 21 '14 at 16:17
-
2[Edsger Dijkstra's Shunting-yard algorithm](https://en.wikipedia.org/wiki/Shunting-yard_algorithm) – David Conrad Apr 21 '14 at 16:27
-
possible duplicate of [Equation (expression) parser with precedence?](http://stackoverflow.com/questions/28256/equation-expression-parser-with-precedence) – Zoyd Apr 21 '14 at 16:33
1 Answers
0
With JDK1.6, you can use the built-in Javascript engine.
this is tested and working .
import java.io.*;
import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;
import java.util.Scanner;
import javax.script.ScriptException;
public class MathExpress {
public static void main(String[] args) throws ScriptException {
Scanner console = new Scanner(System.in);
System.out.println("Enter your arithematic oparation ");
String Mathex= console.nextLine();
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("JavaScript");
System.out.println(engine.eval(Mathex));
}
}

Madhawa Priyashantha
- 9,633
- 7
- 33
- 60