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 ...
随机推荐
- siblings 使用
//$(object).siblings().each(function () { // $(this).find("img").attr("class", & ...
- [Mobile] 手机浏览器输入框-数字输入框
手机浏览器的输入框,一直都是以web的方式进行开发的,没有关注到用户体验,领导提出了输入框要弹出数字输入框,想来应该有这种技术能实现. 搜索之后发现可以使用type="number&qu ...
- 第九篇:在SOUI中使用多语言翻译
为UI在不同地区显示不同的语言是产品国际化的一个重要要求. 在SOUI中实现了一套类似QT的多语言翻译机制:布局XML不需要调整,程序代码也不需要调整,只需要为不同地区的用户提供不同的语言翻译文件即可 ...
- ubuntu初始化root帐号密码
Ubuntu Kylin 14.04的安装过程中并没有提供设置root密码的过程,取而代之的是自定义的帐号. 如果我们需要使用到root帐号或者root权限,则需要重新设置root帐号的密码. 设置方 ...
- 在Asp.Net MVC中实现CompareValues标签对Model中的属性进行验证
在Asp.Net MVC中可以用继承ValidationAttribute的方式,自定制实现Model两个中两个属性值的比较验证 具体应用场景为:要对两个属性值的大小进行验证 代码如下所示: /// ...
- 在Salesforce中创建Web Service供外部系统调用
在Salesforce中可以创建Web Service供外部系统调用,并且可以以SOAP或者REST方式向外提供调用接口,接下来的内容将详细讲述一下用SOAP的方式创建Web Service并且用As ...
- VPS -Digital Ocean -搭建一个最简单的web服务器
简单的也是美的 在一个目录放自己的几个showcase网页方便和别人分享,最简单的方式是什么 创建文件夹,放入自己的网页文件 在目录下执行 $ nohup python -m SimpleHTTPSe ...
- python学习第三天
小结: 总体上,python是解释型语言,开源比较好,速度较慢,装逼神器,解释器较常用的是CPython,安装后python进入运行环境 exit()退出 第一个hello world : print ...
- 非正规写法获取不到tr,td
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title> ...
- Oracle资源
ORACLE 10g下载地址 oracle 下载还需要用户名我自己注册了个方便大家使用下载 user:1603869780@qq.compass:qwe123QWE现在直接点击不能下载了 要经过ora ...