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:判断字符串是否为数字的五种方法
Java:判断字符串是否为数字的五种方法 //方法一:用JAVA自带的函数 public static boolean isNumeric(String str){ for (int i = str. ...
- Java中判断字符串是否为数字的五种方法
//方法一:用JAVA自带的函数 public static boolean isNumeric(String str){ for (int i = str.length();--i>=0;){ ...
- Java中判断字符串是否为数字的五种方法 (转)
推荐使用第二个方法,速度最快. 方法一:用JAVA自带的函数 public static boolean isNumeric(String str){ for (int i = str.length( ...
- 【工具类】Java中判断字符串是否为数字的五种方法
1 //方法一:用JAVA自带的函数 2 public static boolean isNumeric(String str){ 3 for (int i = str.length();--i> ...
- java中判断字符串是否为数字的三种方法
以下内容引自 http://www.blogjava.net/Javaphua/archive/2007/06/05/122131.html 1用JAVA自带的函数 public static ...
- java判断一个字符串是否是数字的三种方法
参考https://blog.csdn.net/ld_flex/article/details/7699161 1 用JAVA自带的函数 public static boolean isNumeric ...
- [转]java中判断字符串是否为数字的三种方法
1用JAVA自带的函数public static boolean isNumeric(String str){ for (int i = str.length();--i>=0;){ ...
- Java 判断字符串是否为空的四种方法、优缺点与注意事项
以下是Java 判断字符串是否为空的四种方法: 方法一: 最多人使用的一个方法, 直观, 方便, 但效率很低: if(s == null ||"".equals(s));方法二: ...
- String空格删除和java删除字符串最后一个字符的几种方法
1. String.trim()trim()是去掉首尾空格2.str.replace(" ", ""); 去掉所有空格,包括首尾.中间复制代码 代码如下:Str ...
随机推荐
- java 泛型 -- 泛型类,泛型接口,泛型方法
泛型T泛型的许多最佳例子都来自集合框架,因为泛型让您在保存在集合中的元素上指定类型约束.在定义泛型类或声明泛型类的变量时,使用尖括号来指定形式类型参数.形式类型参数与实际类型参数之间的关系类似于形式方 ...
- 几年前做家教写的C教程(之一)
C语言学习宝典 首先让我们认识什么是C语言. C语言是一种计算机开发语言,是一种非常基础的开发语言.能够用C语言做很多事情.C语言是顺序执行的程序. 程序应该包括数据描述,数据操作. C语言的数据类型 ...
- 11g Physical Standby配置
一,准备 Database DB_UNIQUE_NAME Oracle Net Service Name Primary PROD PROD Physical standby PRODDG PRO ...
- c++ 左值右值 函数模板
1.先看一段代码,这就是一种函数模板的用法,但是红色的部分如果把a写成a++或者写成一个常量比如1,都是编译不过的,因为如果是a++的话,实际上首先是取得a的 值0,而0作为一个常量没有地址.写成1也 ...
- hdu 5000 dp **
题目中提到 It guarantees that the sum of T[i] in each test case is no more than 2000 and 1 <= T[i]. 加 ...
- eclipse项目中关于导入的项目里提示HttpServletRequest 不能引用的解决办法
eclipse项目中关于导入的项目里提示HttpServletRequest 不能引用的解决办法 当使用eclipse导入外部的web工程时,有时会提示HttpServletRequest, Serv ...
- Tips for OpenMesh
OpenMesh 求两点之间的距离 MyMesh::Point p1(1,2,3); MyMesh::Point p2(1,2,5); double d=(p1-p2).length();
- FrameLayout
FrameLayout是最简单的布局了. ① 所有放在布局里的控件,都按照层次堆叠在屏幕的左上角.后加进来的控件覆盖前面的控件. ② 该布局container可以用来占有屏幕的某块区域来显示单一的对象
- 【Filter 不登陆无法访问】web项目中写一个过滤器实现用户不登陆,直接给链接,无法进入页面的功能
在web项目中写一个过滤器实现用户不登陆,直接给链接,无法进入页面,而重定向到登陆界面的功能. 项目是用springMVC+spring+hibernate实现 (和这个没有多大关系) 第一步: 首先 ...
- 【maven 报错】maven项目执行maven install时报错Error assembling WAR: webxml attribute is required (or pre-existing WEB-INF/web.xml if executing in update mode)
在使用maven新建的web项目中,执行 执行如上的这两个操作,报错: [ERROR] Failed to execute goal org.apache.maven.plugins:maven-co ...