(转载)栈

tyut_fantao 2012-09-14 05:53:01
package sweexamination.level1;

import java.util.*;
import java.util.regex.*;
import java.lang.*;

public class AA {

/**
* @param args
*/
/*
* 在回答你的问题之前 做两个说明! 1. 你的输入要合法(不含字母,运算符后有且必须有数字,中间不能有空格)
*/

static String[] operater = new String[20];
static String[] number = new String[20];

public int countExpression(String str) {

Stack countStack1 = new Stack();
Stack countStack2 = new Stack();
int result = 0;
number = str.split("\\/|\\*|\\+|\\-");
operater = str.split("\\d+");
for (int i = 0; i < number.length; i++) {
countStack1.push(number[i]);
if (i != number.length - 1) {
countStack1.push(operater[i + 1]);

}
}
while (!countStack1.isEmpty())
countStack2.push(countStack1.pop());
String op;
while (!countStack2.isEmpty()) {
result = 0;
op = countStack2.pop().toString();
if (op.equals("*")) {
result = Integer.parseInt(countStack1.pop().toString())
* Integer.parseInt(countStack2.pop().toString());
countStack1.push(result);

continue;
}
if (op.equals("/")) {
result = Integer.parseInt(countStack1.pop().toString())
/ Integer.parseInt(countStack2.pop().toString());
countStack1.push(result);
continue;
}
countStack1.push(op);

}
while (!countStack1.isEmpty())
countStack2.push(countStack1.pop());

while (!countStack2.isEmpty()) {
result = 0;
op = countStack2.pop().toString();
if (op.equals("+")) {
result = Integer.parseInt(countStack1.pop().toString())
+ Integer.parseInt(countStack2.pop().toString());
countStack1.push(result);
continue;
}
if (op.equals("-")) {
result = Integer.parseInt(countStack1.pop().toString())
- Integer.parseInt(countStack2.pop().toString());
countStack1.push(result);
continue;
}
countStack1.push(op);

}
return result;
// System.out.println(result);

}

public static void main(String[] args) {
int num;
AA ct = new AA();
num = ct.countExpression("1+2*6-12+5*2");
System.out.println(num);


}

}
...全文
46 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

23,407

社区成员

发帖
与我相关
我的任务
社区描述
Java 非技术区
社区管理员
  • 非技术区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧