Answer to Question #53261 in Java | JSP | JSF for rajashree g.s.
2015-07-07T11:59:07-04:00
I want a code for calculator program in java. For example 9+2-5*8/3. I want a final answer for this.
Like for the whole expression i want the final answer sir.
1
2015-07-09T02:35:51-0400
* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package simplecalculator; import java.util.Scanner; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import javax.script.ScriptException; public class SimpleCalculator { public final static String EXPRESSIONS[] = { "9+2-5*8/3", "(15-6)*9-1" }; public static void main(String[] args) { final ScriptEngineManager engineManager = new ScriptEngineManager(); final ScriptEngine engine = engineManager.getEngineByName("JavaScript"); //------Demo--------------------- for(String s: EXPRESSIONS) { try { System.out.println(s + "=" + engine.eval(s)); } catch (ScriptException ex) { System.err.println("Unsupported expression!"); System.err.println(ex.getMessage()); } } //------Interact with user------- Scanner sc = new Scanner(System.in); System.out.println("Enter expression or 'q' to exit:"); String s = sc.nextLine(); while(!s.equals("q")) { try { System.out.println(engine.eval(s)); } catch (ScriptException ex) { System.err.println("Unsupported expression!"); System.err.println(ex.getMessage()); } System.out.println("Enter expression or 'q' to exit:"); s = sc.nextLine(); } } }
Need a fast expert's response?
Submit order
and get a quick answer at the best price
for any assignment or question with DETAILED EXPLANATIONS !
Learn more about our help with Assignments:
Java JSP JSF
Comments
Leave a comment