Answer to Question #53261 in Java | JSP | JSF for rajashree g.s.

Question #53261
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
Expert's answer
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!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
APPROVED BY CLIENTS