Java.docx
- 文档编号:14478793
- 上传时间:2023-06-23
- 格式:DOCX
- 页数:15
- 大小:18.42KB
Java.docx
《Java.docx》由会员分享,可在线阅读,更多相关《Java.docx(15页珍藏版)》请在冰点文库上搜索。
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){
List
returndoEval(list);//真正求值
}
//遇到操作符压栈,遇到表达式从后缀表达式中弹出两个数,计算出结果,压入堆栈
privatedoubledoEval(List
Stack
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("/"); } privateList List StringBuffernumBuffer=newStringBuffer();//用来保存一个数的 Stack 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 ∙ ∙ 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 ∙ while (matcher.find()) { ∙ list.add(matcher.group()); ∙ } ∙ String[] result = new String[list.size()]; ∙ return list.toArray(result); ∙ } ∙ ∙ public List ∙ 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 ∙ 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 ∙ 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) { ∙
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- Java