public class Test {
 
 public static void main(String[] args) {
 
  SimpleCalculator s=new SimpleCalculator();
 String methord="80*(1+0.5)"; //test
  double d=s.evaluate(methord );
  System.out.println(d);
 }
}
 
 
 
 
import java.util.Scanner;
import java.util.Stack;
public class SimpleCalculator {
 
 
 /**
  * Evaluate an arithmetic expression, and return the result as a double.
  *
  * @param input
  * the expression to evaluate.
  * @return the evaluated result.
  */
 public double evaluate(String input) {
  initialize();
  this.scanner = new Scanner(input);
  this.scanner
    .useDelimiter("\\s+|(?=[.0-9])(?<![.0-9])|(?![.0-9])(?<=[.0-9])|(?![.0-9])(?<![.0-9])");
  Token currentToken = nextToken();
  Token t = null;
  while (null != currentToken) {
   switch (currentToken.getKind()) {
   case NUMBER:
    // Simply push number tokens onto the evaluation stack.
    this.eval.push(currentToken.getValue());
    break;
   case LPAREN:
    // Simply push left parenthesis tokens onto the operator stack.
    this.ops.push(currentToken);
    break;
   case RPAREN:
    // Until a left parenthesis pops off the operator stack, keep
    // poping operators and execute them.
    // If the stack becomes empty without a matching left
    // parenthesis,
    // the expression must have syntax errors.
    for (t = this.ops.pop(); TokenKind.LPAREN != t.getKind(); t = this.ops
      .pop()) {
     if (ops.empty())
      throw new Error("Syntax Error: unmatched parenthesis");
     doOperation(t);
    }
    break;
   default:
    // For binary arithmetic operators, keep poping operators whose
    // binding power
    // is less or equal to the current token's and execute them;
    // after that push
    // the current token onto the operator stack.
    if (!ops.empty()) {
     for (t = this.ops.pop(); currentToken.getKind()
       .getBindingPower() < t.getKind().getBindingPower(); t = this.ops
       .pop()) {
      doOperation(t);
      if (this.ops.empty()) {
       t = null;
       break;
      }
     }
    }
    if (null != t)
     ops.push(t);
    ops.push(currentToken);
    break;
   }
   // reinitialize
   currentToken = nextToken();
  }
  // execute remaining operators on stack
  while (!ops.empty()) {
   t = this.ops.pop();
   doOperation(t);
  }
  // the result is on the top of evaluation stack,
  // pop it off and return the result.
  return this.eval.pop();
 }
 /*
  * Initialize the evaluation and operator stacks.
  */
 private void initialize() {
  if (null == this.eval)
   this.eval = new Stack<Double>();
  if (null == this.ops)
   this.ops = new Stack<Token>();
  this.eval.clear();
  this.ops.clear();
 }
 /*
  * Return the next token from the input expression. The token returned will
  * be associated with its numeric value, if and only if the token is a
  * number.
  */
 private Token nextToken() {
  Token t = null;
  if (this.scanner.hasNextDouble()) {
   t = new Token(TokenKind.NUMBER, this.scanner.nextDouble());
  } else if (this.scanner.hasNext()) {
   String s = this.scanner.next("[-+*/()]");
   if ("+".equals(s)) {
    t = new Token(TokenKind.ADD);
   } else if ("-".equals(s)) {
    t = new Token(TokenKind.SUBTRACT);
   } else if ("*".equals(s)) {
    t = new Token(TokenKind.MULTIPLY);
   } else if ("/".equals(s)) {
    t = new Token(TokenKind.DIVIDE);
   } else if ("(".equals(s)) {
    t = new Token(TokenKind.LPAREN);
   } else if (")".equals(s)) {
    t = new Token(TokenKind.RPAREN);
   }
  }
  return t;
 }
 /*
  * Execute a binary arithmetic operation. Pop the top two values off the
  * evaluation stack, do the operation, and then push the result back onto
  * the evaluation stack.
  */
 private void doOperation(Token t) {
  double y = this.eval.pop();
  double x = this.eval.pop();
  double temp = t.getKind().doOperation(x, y);
  this.eval.push(temp);
 }
 /*
  * Tokenizer for the input expression.
  */
 private Scanner scanner;
 /*
  * Evaluation stack.
  */
 private Stack<Double> eval;
 /*
  * Operator stack, for converting infix expression to postfix expression.
  */
 private Stack<Token> ops;
 public static void main(String[] args) {
  if (args.length < 1) {
   System.err.println("Usage: java SimpleCalculator <expression>");
   System.exit(1);
  }
  SimpleCalculator calc = new SimpleCalculator();
  double result = calc.evaluate(args[0]);
  System.out.println(result);
 }
}
enum TokenKind {
 // operators
 ADD(1) {
  public double doOperation(double x, double y) {
   return x + y;
  }
 },
 SUBTRACT(2) {
  public double doOperation(double x, double y) {
   return x - y;
  }
 },
 MULTIPLY(3) {
  public double doOperation(double x, double y) {
   return x * y;
  }
 },
 DIVIDE(4) {
  public double doOperation(double x, double y) {
   return x / y;
  }
 },
 // punctuation
 LPAREN(0), RPAREN(0),
 // number
 NUMBER(0);
 TokenKind(int bindingPower) {
  this.bindingPower = bindingPower;
 }
 public int getBindingPower() {
  return this.bindingPower;
 }
 public double doOperation(double x, double y) {
  return Double.NaN; // dummy, operation not supported
 }
 private int bindingPower;
}
class Token {
 public Token(TokenKind kind) {
  this(kind, Double.NaN);
 }
 public Token(TokenKind kind, double value) {
  this.kind = kind;
  this.value = value;
 }
 public TokenKind getKind() {
  return this.kind;
 }
 public double getValue() {
  return this.value;
 }
 private TokenKind kind;
 private double value;
}

【JAVA】通过公式字符串表达式计算值,网上的一种方法的更多相关文章

  1. Java:判断字符串是否为数字的五种方法

    Java:判断字符串是否为数字的五种方法 //方法一:用JAVA自带的函数 public static boolean isNumeric(String str){ for (int i = str. ...

  2. Java中判断字符串是否为数字的五种方法

    //方法一:用JAVA自带的函数 public static boolean isNumeric(String str){ for (int i = str.length();--i>=0;){ ...

  3. Java中判断字符串是否为数字的五种方法 (转)

    推荐使用第二个方法,速度最快. 方法一:用JAVA自带的函数 public static boolean isNumeric(String str){ for (int i = str.length( ...

  4. 【工具类】Java中判断字符串是否为数字的五种方法

    1 //方法一:用JAVA自带的函数 2 public static boolean isNumeric(String str){ 3 for (int i = str.length();--i> ...

  5. java中判断字符串是否为数字的三种方法

    以下内容引自  http://www.blogjava.net/Javaphua/archive/2007/06/05/122131.html 1用JAVA自带的函数   public static ...

  6. java判断一个字符串是否是数字的三种方法

    参考https://blog.csdn.net/ld_flex/article/details/7699161 1 用JAVA自带的函数 public static boolean isNumeric ...

  7. [转]java中判断字符串是否为数字的三种方法

    1用JAVA自带的函数public static boolean isNumeric(String str){  for (int i = str.length();--i>=0;){      ...

  8. Java 判断字符串是否为空的四种方法、优缺点与注意事项

    以下是Java 判断字符串是否为空的四种方法: 方法一: 最多人使用的一个方法, 直观, 方便, 但效率很低: if(s == null ||"".equals(s));方法二: ...

  9. String空格删除和java删除字符串最后一个字符的几种方法

    1. String.trim()trim()是去掉首尾空格2.str.replace(" ", ""); 去掉所有空格,包括首尾.中间复制代码 代码如下:Str ...

随机推荐

  1. MVC4 使用概述

    1.Bundle使用: http://www.cnblogs.com/inline/p/3897256.html 2.MVC总结: http://www.cnblogs.com/xlhblogs/ar ...

  2. catch that cow (bfs 搜索的实际应用,和图的邻接表的bfs遍历基本上一样)

    Catch That Cow Time Limit: 2000MS   Memory Limit: 65536K Total Submissions: 38263   Accepted: 11891 ...

  3. HDU4495 Rectangle

    求组成的等腰三角形面积最大值. 对此题的总结:暴力出奇迹 组成的三角形放置方式一共只有4种,用ans表示目前已知的最长三角形的边长,从上到下,从左到右枚举顶点,再枚举边长,一个重要剪枝是枚举边长l时先 ...

  4. Visual Studio 2015将在7月20号RTM

    (此文章同时发表在本人微信公众号"dotNET每日精华文章",欢迎右边二维码来关注.) 题记:用了3个多月的VS 2015终于要迎来RTM了,不过感觉有点淡淡的忧伤(为什么呢?请看 ...

  5. 常见IE浏览器bug及其修复方案(双外边距、3像素偏移、绝对定位)

    1. 双外边距浮动bug IE6和更低版本中存在双外边距浮动bug,顾名思义,这个Windows bug使任何浮动元素上的外边距加倍 bug重现: <!DOCTYPE html> < ...

  6. android:layout_weight属性详解 (转)

    在android开发中LinearLayout很常用,LinearLayout的内控件的android:layout_weight在某些场景显得非常重要,比如我们需要按比例显示.android并没用提 ...

  7. 程序员应该是使用git

    我来梳理下我想用git做的事情应该拥有那些功能: 本地的git命令以及图形界面,好让我在没有联网的时候创建git版本控制记录历史功能 一个github账号,好让我可以把本地的git仓库同步到那里 功能 ...

  8. 遍历PspCidTable表检测隐藏进程

    一.PspCidTable概述 PspCidTable也是一个句柄表,其格式与普通的句柄表是完全一样的,但它与每个进程私有的句柄表有以下不同: 1.PspCidTable中存放的对象是系统中所有的进程 ...

  9. Intent界面跳转与传递数据

    Activity跳转与传值,主要是通过Intent类,Intent的作用是激活组件和附带数据. intent可以激活Activity,服务,广播三类组件. 本博文讲的是显示意图激活Activity组件 ...

  10. HDU 4496 D-City (并查集)

    题意:有n个城市,m条路,首先m条路都连上,接着输出m行,第i行代表删除前i行的得到的连通块个数 题解:正难则反,我们反向考虑使用并查集添边.首先每个点都没有相连,接着倒着来边添加边计算,当两个点父节 ...