Java.docx

上传人:b****3 文档编号:26891171 上传时间:2023-06-23 格式:DOCX 页数:15 大小:18.42KB
下载 相关 举报
Java.docx_第1页
第1页 / 共15页
Java.docx_第2页
第2页 / 共15页
Java.docx_第3页
第3页 / 共15页
Java.docx_第4页
第4页 / 共15页
Java.docx_第5页
第5页 / 共15页
点击查看更多>>
下载资源
资源描述

Java.docx

《Java.docx》由会员分享,可在线阅读,更多相关《Java.docx(15页珍藏版)》请在冰豆网上搜索。

Java.docx

Java

【转】中缀表达式转后缀表达式并求值,经典逆波兰算法,展现堆栈的使用,Java版的公式计算器

Java2009-05-3017:

28:

26阅读569评论0  字号:

大中小 订阅

packagelab6;

importjava.util.ArrayList;

importjava.util.List;

importjava.util.Stack;

importlab2.SavitchIn;

/**

  *

  *@authorBlueNight

  *xiaohuiq8@

  */

publicclassLab6{

   publicdoubleeval(Stringexp){

       Listlist=infixExpToPostExp(exp);//转化成后缀表达式

       returndoEval(list);//真正求值

   }

     

   //遇到操作符压栈,遇到表达式从后缀表达式中弹出两个数,计算出结果,压入堆栈

   privatedoubledoEval(Listlist){

      Stackstack=newStack();

      Stringelement;

      doublen1,n2,result;

      try{

          for(inti=0;i

              element=list.get(i);  

              if(isOperator(element)){

                  n1=Double.parseDouble(stack.pop());

                  n2=Double.parseDouble(stack.pop());

                  result=doOperate(n2,n1,element);

                  stack.push(newDouble(result).toString());

             }else{

                stack.push(element);             }

          }

          returnDouble.parseDouble(stack.pop());

      }catch(RuntimeExceptione){

          thrownewIllegalExpressionException(e.getMessage());        

      }

   }     privatedoubledoOperate(doublen1,doublen2,Stringoperator){

      if(operator.equals("+"))

          returnn1+n2;

      elseif(operator.equals("-"))

          returnn1-n2;

      elseif(operator.equals("*"))

          returnn1*n2;

      else

          returnn1/n2;

   }

  

   privatebooleanisOperator(Stringstr){

       returnstr.equals("+")||str.equals("-")||str.equals("*")||str.equals("/");

   }

     

   privateListinfixExpToPostExp(Stringexp){//将中缀表达式转化成为后缀表达式

       ListpostExp=newArrayList();//存放转化的后缀表达式的链表

       StringBuffernumBuffer=newStringBuffer();//用来保存一个数的

       StackopStack=newStack();//操作符栈

       charch,preChar;

       opStack.push('#');

       try{

           for(inti=0;i

              ch=exp.charAt(i);

               switch(ch){

                    case'+':

                    case'-':

                   case'*':

                    case'/':

                        preChar=opStack.peek();

//             如果栈里面的操作符优先级比当前的大,则把栈中优先级大的都添加到后缀表达式列表中                         

                        while(priority(preChar)>=priority(ch)){

                            postExp.add(""+preChar);

                            opStack.pop();

                            preChar=opStack.peek();

                        }

                        opStack.push(ch);

                        i++;  

                        break;

                   case'(':

//             左括号直接压栈

                        opStack.push(ch);

                        i++;

                        break;

                   case')':

//             右括号则直接把栈中左括号前面的弹出,并加入后缀表达式链表中

                        charc=opStack.pop();

                        while(c!

='('){

                            postExp.add(""+c);

                            c=opStack.pop();//'c'是'('时不要添加到输出字符串中了

                        }

                        i++;

                        break;

//          #号,代表表达式结束,可以直接把操作符栈中剩余的操作符全部弹出,并加入后缀表达式链表中

                 case'#':

                     charc1;

                     while(!

opStack.isEmpty()){

                         c1=opStack.pop();

                         if(c1!

='#')

                           postExp.add(""+c1);

                     }

                     i++;

                     break;

                              //过滤空白符

                 case'':

                 case'\t':

                     i++;

                     break;

//              数字则凑成一个整数,加入后缀表达式链表中

                 default:

                     if(Character.isDigit(ch)){

                         while(Character.isDigit(ch)){

                             numBuffer.append(ch);

                             ch=exp.charAt(++i);

                         }

                         postExp.add(numBuffer.toString());

                         numBuffer=newStringBuffer();

                     }else{

                         thrownewIllegalExpressionException("illegaloperator");

                     }

               }

           }

       }catch(RuntimeExceptione){

           thrownewIllegalExpressionException(e.getMessage());  

      }

       returnpostExp;

   }

    

   privateintpriority(charop){//定义优先级

        switch(op){

        case'+':

        case'-':

            return1;

        case'*':

        case'/':

            return2;

        case'(':

        case'#':

            return0;

        }

        thrownewIllegalExpressionException("Illegaloperator");

  }

    //main

   publicstaticvoidmain(String[]args){

       Lab6eval=newLab6();

       

       System.out.println("输入公式");

       Strings=SavitchIn.readLine();

       s=s+"#";

       doubleresult=eval.eval(s);

       System.out.println(result);

       

   }

}

//继承异常

classIllegalExpressionExceptionextendsRuntimeException{

          

        /**

   *

   */

   privatestaticfinallongserialVersionUID=1L;

      publicIllegalExpressionException(){

              

        }

          

        publicIllegalExpressionException(Stringinfo){

           super(info);

        }

 

∙package com.JRIAS;  

∙  

∙import java.math.BigDecimal;  

∙import java.util.ArrayList;  

∙import java.util.List;  

∙import java.util.regex.Matcher;  

∙import java.util.regex.Pattern;  

∙  

∙/** 

∙ *  

∙ * 应用:

逆波兰表达式 

∙ *  

∙ * @author Leon.Chen 

∙ * gxqxmh@ www.JRIAS.com 

∙ */  

∙public class CalculateString {  

∙  

∙    public BigDecimal calculateString(String str) {  

∙        char[] strs = str.toCharArray();  

∙        Stack stack = new Stack();  

∙  

∙        for (int i = 0; i < strs.length; i++) {  

∙            String stackStr = String.valueOf(strs[i]);  

∙            stack.push(stackStr);  

∙            if (")".equals(stack.top())) {  

∙                String subStr = null;  

∙                while (!

"(".equals(stack.top())) {  

∙                    stack.pop();  

∙                    if (!

"(".equals(stack.top())) {  

∙                        subStr = addEnd(subStr, stack.top());  

∙                    }  

∙                }  

∙                String pushStr = CalculateReversePolishExpression(subStr);  

∙                stack.pop();  

∙                stack.push(pushStr);  

∙            }  

∙  

∙        }  

∙        String resultStr = null;  

∙        while (stack.count !

= 0) {  

∙            resultStr = CalculateReversePolishExpression(stack.toString());  

∙        }  

∙        BigDecimal result = null;  

∙        if (resultStr !

= null) {  

∙            result = new BigDecimal(resultStr);  

∙        } else {  

∙            result = BigDecimal.ZERO;  

∙        }  

∙        return result.setScale(2, BigDecimal.ROUND_HALF_UP);  

∙    }  

∙  

∙    public String[] matcher(String regex, String str) {  

∙        Pattern pattern = Ppile(regex);  

∙        Matcher matcher = pattern.matcher(str);  

∙        List list = new ArrayList();  

∙        while (matcher.find()) {  

∙            list.add(matcher.group());  

∙        }  

∙        String[] result = new String[list.size()];  

∙        return list.toArray(result);  

∙    }  

∙  

∙    public List createReversePolishExpression(String subStr) {  

∙        String regex = "\\d+\\.{0,1}\\d*";  

∙        String[] numbers = matcher(regex, subStr);  

∙        String changeStr = subStr.replaceAll(regex, "0").replaceAll("\\-\\-0",  

∙                "-1").replaceAll("\\+\\-0", "+1").replaceAll("\\*\\-0", "*1")  

∙                .replaceAll("\\/\\-0", "/1");  

∙        char[] chars = changeStr.toCharArray();  

∙        int index = 0;  

∙        List list = new ArrayList();  

∙        for (int i = 0; i < chars.length; i++) {  

∙            String str = String.valueOf(chars[i]);  

∙            if ("0".equals(str)) {  

∙                list.add(numbers[index++]);  

∙            } else if ("1".equals(str)) {  

∙                list.add("-" + numbers[index++]);  

∙            } else {  

∙                list.add(str);  

∙            }  

∙        }  

∙        List suffix = new ArrayList();  

∙        Stack operator = new Stack();  

∙        for (int i = 0; i < list.size(); i++) {  

∙            if (!

isOperatorType(list.get(i))) {  

∙                suffix.add(list.get(i));  

∙            } else {  

∙                if (operator.count == 0) {  

∙                    operator.push(list.get(i));  

∙                } else {  

∙                    while (operator.count !

= 0&&compare(operator.top(), list.get(i)) >= 0) {  

∙                        String top = operator.top();  

∙                        operator.pop();  

∙                        suffix.add(top);  

∙                    }   

∙                    operator.push(list.get(i));  

∙  

∙                }  

∙            }  

∙        }  

∙  

∙        while (operator.count !

= 0) {  

∙            suffix.add(operator.top());  

∙            operator.pop();  

∙        }  

∙        return suffix;  

∙    }  

∙  

∙    public String CalculateReversePolishExpression(String subStr) {  

∙  

展开阅读全文
相关资源
猜你喜欢
相关搜索

当前位置:首页 > 总结汇报 > 其它

copyright@ 2008-2022 冰豆网网站版权所有

经营许可证编号:鄂ICP备2022015515号-1