Java实现四则运算表达式计算
| [日期:2012-09-08] |
来源:Linux社区
作者:lip009 |
[字体:大 中 小]
|
-
-
-
-
-
- public class Arithmetic {
- public static void main(String args[]){
- System.out.println(arithmetic("2.2+((3+4)*2-22)/2*3.2"));
- }
- public static double arithmetic(String exp){
- String result = parseExp(exp).replaceAll("[\\[\\]]", "");
- return Double.parseDouble(result);
- }
-
-
-
-
-
- public static String parseExp(String expression){
-
- expression=expression.replaceAll("\\s+", "").replaceAll("^\\((.+)\\)$", "$1");
- String checkExp="\\d";
- String minExp="^((\\d+(\\.\\d+)?)|(\\[\\-\\d+(\\.\\d+)?\\]))[\\+\\-\\*\\/]((\\d+(\\.\\d+)?)|(\\[\\-\\d+(\\.\\d+)?\\]))$";
-
- if(expression.matches(minExp)){
- String result=calculate(expression);
-
- return Double.parseDouble(result)>=0?result:"["+result+"]";
- }
-
- String noParentheses="^[^\\(\\)]+$";
- String priorOperatorExp="(((\\d+(\\.\\d+)?)|(\\[\\-\\d+(\\.\\d+)?\\]))[\\*\\/]((\\d+(\\.\\d+)?)|(\\[\\-\\d+(\\.\\d+)?\\])))";
- String operatorExp="(((\\d+(\\.\\d+)?)|(\\[\\-\\d+(\\.\\d+)?\\]))[\\+\\-]((\\d+(\\.\\d+)?)|(\\[\\-\\d+(\\.\\d+)?\\])))";
- if(expression.matches(noParentheses)){
- Pattern patt=Pattern.compile(priorOperatorExp);
- Matcher mat=patt.matcher(expression);
- if(mat.find()){
- String tempMinExp=mat.group();
- expression=expression.replaceFirst(priorOperatorExp, parseExp(tempMinExp));
- }else{
- patt=Pattern.compile(operatorExp);
- mat=patt.matcher(expression);
-
- if(mat.find()){
- String tempMinExp=mat.group();
- expression=expression.replaceFirst(operatorExp, parseExp(tempMinExp));
- }
- }
- return parseExp(expression);
- }
-
- String minParentheses="\\([^\\(\\)]+\\)";
- Pattern patt=Pattern.compile(minParentheses);
- Matcher mat=patt.matcher(expression);
- if(mat.find()){
- String tempMinExp=mat.group();
- expression=expression.replaceFirst(minParentheses, parseExp(tempMinExp));
- }
- return parseExp(expression);
- }
-
-
-
-
-
- public static String calculate(String exp){
- exp=exp.replaceAll("[\\[\\]]", "");
- String number[]=exp.replaceFirst("(\\d)[\\+\\-\\*\\/]", "$1,").split(",");
- BigDecimal number1=new BigDecimal(number[0]);
- BigDecimal number2=new BigDecimal(number[1]);
- BigDecimal result=null;
-
- String operator=exp.replaceFirst("^.*\\d([\\+\\-\\*\\/]).+$", "$1");
- if("+".equals(operator)){
- result=number1.add(number2);
- }else if("-".equals(operator)){
- result=number1.subtract(number2);
- }else if("*".equals(operator)){
- result=number1.multiply(number2);
- }else if("/".equals(operator)){
- result=number1.divide(number2);
- }
-
- return result!=null?result.toString():null;
- }
- }

评论声明
- 尊重网上道德,遵守中华人民共和国的各项有关法律法规
- 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
- 本站管理人员有权保留或删除其管辖留言中的任意内容
- 本站有权在网站内转载或引用您的评论
- 参与本评论即表明您已经阅读并接受上述条款
|
|
第 2 楼 匿名 发表于 2013/1/21 11:39:09效率比起JavaScript,实在差得太远 第 1 楼 匿名 发表于 2012/10/30 9:01:35这个支持不了负数
|
|