点击这里给我发消息 点击这里给我发消息

Java中使用javascript实现计算器功能

添加时间:2013-12-7
    相关阅读: 系统

  不废话,直接上代码: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);

  }

  }

咨询热线:020-85648757 85648755 85648616 0755-27912581 客服:020-85648756 0755-27912581 业务传真:020-32579052
广州市网景网络科技有限公司 Copyright◎2003-2008 Veelink.com. All Rights Reserved.
广州商务地址:广东省广州市黄埔大道中203号(海景园区)海景花园C栋501室
= 深圳商务地址:深圳市宝源路华丰宝源大厦606
研发中心:广东广州市天河软件园海景园区 粤ICP备05103322号 工商注册