怎么将带括号的中缀表达式转变为后缀表达式?
最后带有解释的代码
最后带有解释的代码
解决方案 »
- struts
- 向数据库插入字符数据时,出现空格,造成无法查询
- 新手求教:SWT中如何实现undo/redo
- 关于设置swing快捷键的问题!! 当设ESC为快捷键时,好像没什么效果
- 怎样不显示model中某一列的数据?(在jtable中)
- java.sql.SQLException: [BEA][SQLServer JDBC Driver]No more data available to read..>
- 关于DTD的问题(100分!!!!!)
- java反编译软件哪里可以下载
- Jbuilder 新手遇到难题啦!
- 希望了解java,能推荐一个好的开发工具和一本好的入门书籍吗?我以前直到现在都在用VC,接下来想在C#和java中选一个做为第二语言。
- 怎样做一个月历
- 如何让数组降序排列
private String src;
/**
* constructor
* @param src the string(expression) to calculate
*/
public CalStr(String src) {
this.src = src;
}
/**
* calculate to get the result
* @return (double)result
*/
public double getResult() {
String postfix = getPostfix();
Stack<String> stk = new Stack<String>();
//System.out.println(postfix);
String parts[] = postfix.split(" +");
double result=0;
for(int i=0; i<parts.length; i++){
char tmp = parts[i].charAt(0);
if(!isOperator(tmp)){
stk.push(parts[i]);
}
else{
double a = Double.parseDouble(stk.pop());
double b = Double.parseDouble(stk.pop());
//b is followed by a in the orignal expression
result = calculate(b,a,tmp);
stk.push(String.valueOf(result));
}
}
return result;
}
/**
* test if the character is an operator,such +,-,*,/
* @param op the character to test
* @return true if op is an operator otherwise false
*/
private boolean isOperator(char op){
return (op=='+'||op=='-'||op=='*'||op=='/');
}
/**
* calculate an expression such (a op b)
* @param a number 1
* @param b number 2
* @param op the operator
* @return (double)(a op b)
*/
public double calculate(double a, double b, char op) {
switch (op) {
case '+':
return a + b;
case '-':
return a - b;
case '*':
return a * b;
case '/':
return a / b;
}
return -1;
}
/**
* convert the suffix to postfix
* @return the postfix as a string
*/
private String getPostfix() {
Stack<String> stk = new Stack<String>();
String postfix = new String();
char op;
int i = 0;
while (i < src.length()) {
if (Character.isDigit(src.charAt(i))||src.charAt(i)=='.') {
postfix += " ";
do {
postfix += src.charAt(i++);
} while ((i < src.length())
&& (Character.isDigit(src.charAt(i))));
postfix += " ";
} else {
switch (op = src.charAt(i++)) {
case '(':
stk.push("(");
break;
case ')':
while (stk.peek() != "(") {
String tmp = stk.pop();
postfix += tmp;
if(tmp.length()==1 && isOperator(tmp.charAt(0)))
postfix += " ";
}
stk.pop();
postfix += " ";
break;
case '+':
case '-':
while ((!stk.empty()) && (stk.peek() != "(")) {
postfix += stk.pop()+" ";
}
stk.push(new Character(op).toString());
break;
case '*':
case '/':
while ((!stk.empty())
&& ((stk.peek() == "*") || (stk.peek() == "/"))) {
postfix += stk.pop()+" ";
}
stk.push(new Character(op).toString());
break;
}
}
}
ListIterator it = stk.listIterator(stk.size());
while (it.hasPrevious())
postfix += it.previous() + " ";
return postfix.trim().replaceAll(" +\\.",".");
} /**
* main function
* @param args
*/
public static void main(String args[]) {
System.out.println(new CalStr("((1.5+6.000)*9+9.36)*(8+9-8*8+8*7)").getResult());
}
}