publicclassTest {publicstaticvoidmain(String[] args) {
String str="40944.0501-3.2*100";
Calculator cal=newCalculator();doubled=cal.eval(str);
System.out.println(d);
}
}publicinterfaceMathSymbol {/*** 左括号*/publicfinalstaticcharLEFT_BRACKET='(';/*** 右括号*/publicfinalstaticcharRIGHT_BRACKET=')';/*** 中缀表达式中的空格,需要要忽略*/publicfinalstaticcharBLANK='';/*** 小数点符号*/publicfinalstaticcharDECIMAL_POINT='.';/*** 负号*/publicfinalstaticcharNEGATIVE_SIGN='-';/*** 正号*/publicfinalstaticcharPOSITIVE_SIGN='+';/*** 后缀表达式的各段的分隔符*/publicfinalstaticcharSEPARATOR='';
}importjava.util.Stack;publicclassCalculatorimplementsMathSymbol {/*** 计算中缀表达式
*@paramexpression
*@return*/publicdoubleeval(String expression) {
String str=infix2Suffix(expression);//System.out.println(" Infix Expression: " + expression);//System.out.println("Suffix Expression: " + str);if(str==null) {thrownewIllegalArgumentException("Expression is null!");
}
String[] strs=str.split("//s+");
Stackstack=newStack();for(inti=0; i
stack.push(strs[i]);
}else{
Operator op=Operator.getInstance(strs[i]);doubleright=Double.parseDouble(stack.pop());doubleleft=Double.parseDouble(stack.pop());doubleresult=op.eval(left, right);
stack.push(String.valueOf(result));
}
}returnDouble.parseDouble(stack.pop());
}/*** 将中缀表达式转换为后缀表达式
*@paramexpression
*@return*/publicString infix2Suffix(String expression) {if(expression==null) {returnnull;
}char[] chs=expression.toCharArray();
Stackstack=newStack();
StringBuilder sb=newStringBuilder(chs.length);booleanappendSeparator=false;booleansign=true;for(inti=0; i
}//Next line is used output stack information.//System.out.printf("%-20s %s%n", stack, sb.toString());if(appendSeparator) {
sb.append(SEPARATOR);
appendSeparator=false;
}if(isSign(c)&&sign) {
sb.append(c);continue;
}if(isNumber(c)) {
sign=false;
sb.append(c);continue;
}if(isLeftBracket(c)) {
stack.push(c);continue;
}if(isRightBracket(c)) {
sign=false;while(stack.peek()!=LEFT_BRACKET) {
sb.append(SEPARATOR);
sb.append(stack.pop());
}
stack.pop();continue;
}
appendSeparator=true;if(Operator.isOperator(c)) {
sign=true;if(stack.isEmpty()||stack.peek()==LEFT_BRACKET) {
stack.push(c);continue;
}intprecedence=Operator.getPrority(c);while(!stack.isEmpty()&&Operator.getPrority(stack.peek())>=precedence) {
sb.append(SEPARATOR);
sb.append(stack.pop());
}
stack.push(c);
}
}while(!stack.isEmpty()) {
sb.append(SEPARATOR);
sb.append(stack.pop());
}returnsb.toString();
}/*** 判断某个字符是否是正号或者负号
*@paramc
*@return*/privatebooleanisSign(charc) {if(c==NEGATIVE_SIGN||c==POSITIVE_SIGN) {returntrue;
}returnfalse;
}/*** 判断某个字符是否为数字或者小数点
*@paramc
*@return*/privatebooleanisNumber(charc) {if((c>='0'&&c<='9')||c==DECIMAL_POINT) {returntrue;
}returnfalse;
}/*** 判断某个字符是否为左括号
*@paramc
*@return*/privatebooleanisLeftBracket(charc) {returnc==LEFT_BRACKET;
}/*** 判断某个字符是否为右括号
*@paramc
*@return*/privatebooleanisRightBracket(charc) {returnc==RIGHT_BRACKET;
}
}