问题:java 解析并计算字符串表达式 “(1+2)*(3+8/(2*2))”
分析:
1.运算的优先级规则如何表达
可以使用括号代替优先级规则表示,优先级高的用括号括起来,优先计算括号内的表达式。
2.计算符号和计算因子的存储和操作
计算符号和计算因子分别存在两个栈(后进先出)中,忽略左括号,当遇到右括号时,弹出一个计算符号和两个计算因子。同时为了方便写程序表达式整体也加到一组括号中,所以字符串表达式更改为:“((1+2)*(3+(8/(2*2))))”
代码如下:
//1.自定义栈,其中包含入栈和出栈方法
public class Stack<T> {
private List<T> list = new ArrayList<>();
public void push(T t){
list.add(t);
}
public T pop(){
T t = list.isEmpty()?null:list.get(list.size() - 1);
list.remove(list.size()-1);
return t;
}
}
//2.表达式解析和计算
public static void main(String[] args) {
String str = "((1+2)*(3+(8/(2*2))))".replaceAll(" ","" );
Stack<String> operationStack = new Stack<String>();
Stack<Integer> integerStack = new Stack<Integer>();
char[] chars = str.toCharArray();
List<String> operations = new ArrayList<>();
operations.add("+");
operations.add("-");
operations.add("/");
operations.add("*");
for(char c:chars){
String sc = c+"";
if(operations.contains(sc)){
operationStack.push(sc);
}else if(")".equals(sc)){
String oper = operationStack.pop();
Integer d1 = integerStack.pop();
Integer d2 = integerStack.pop();
if("+".equals(oper)) integerStack.push(d1+d2);
else if("-".equals(oper)) integerStack.push(d2-d1);
else if("*".equals(oper)) integerStack.push(d1*d2);
else if("/".equals(oper)) integerStack.push(d2/d1);
}else if("(".equals(sc)){
continue;
}else{
integerStack.push(Integer.valueOf(sc));
}
}
System.out.println("计算结果:"+integerStack.pop());//计算结果:15
}
以上代码并未考虑实际开发场景,只适用于个位正整数的计算,仅为表达思路而已,不喜勿喷!