不废话,直接上代码:Java代码
package org.galo.thread;
import java.util.Scanner;
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class Calculator {
private static final String WELCOME_MESSAGE = "请输入计算表达式:(或'exit'退出)";
private static final String EXIT_MESSAGE = "系统正在退出,请稍后";
private static final String QUIT_MESSAGE = "感谢您的使用,再见!";
private static final String ERROR_MESSAGE = "[表达式语法错误]请输入:(或'exit'退出)";
public static void main(String[] args) {
sayWelcome();
main();
}
public static void main() {
Scanner scanner = new Scanner(System.in);
println(WELCOME_MESSAGE);
while(scanner.hasNext()){
String exp = scanner.next();
long startTime = System.currentTimeMillis();
if("exit".equals(exp)){
doExit();
return;
}
String result = evalJS(exp);
if(result == null){
continue;
}
long endTime = System.currentTimeMillis();
println("计算结果:" + result + " ;用时:" + (endTime - startTime) + "ms");
println("");
println(WELCOME_MESSAGE);
}
}
private static void doExit() {
print(EXIT_MESSAGE);
for (int i = 0; i < 6; i++) {
try {
Thread.sleep(500);
print(".");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
println("");
println(QUIT_MESSAGE);
}
public static void sayWelcome() {
println("****************************");
println("*******JAVA计算器V0.1********");
println("**********欢迎使用************");
println("****************************");
}
private static String evalJS(String exp) {
Double result;
ScriptEngineManager sem = new ScriptEngineManager();
ScriptEngine se = sem.getEngineByName("javascript");
String script = "function compute(){return " +
exp +
"};";
try {
se.eval(script);
Invocable invocable = (Invocable) se;
result = (Double) invocable.invokeFunction("compute", new Object[]{});
return result.toString();
} catch (ScriptException e) {
println("");
println(ERROR_MESSAGE);
return null;
} catch (NoSuchMethodException e) {
println("");
println(ERROR_MESSAGE);
return null;
}
}
public static void println(String word){
System.out.println(word);
}
public static void print(String word){
System.out.print(word);
}
}