思路分析
- 先将biaodashi装入一个Arraylist中
- 将Arraylist传递给一个方法,遍历Arraylist 配合栈完成计算
package com.ran;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
public class hello {
public static void main(String[] args) {
//(3+4)*5-6 => 3 4 + 5 x 6 -
//为了方便,数字和符号隔开
String biaodashi="3 4 + 5 * 6 -";
System.out.println(fenge(biaodashi));
System.out.println(fenge(biaodashi));
System.out.println(jisuan(fenge(biaodashi)));
}
public static List<String> fenge(String biaodashi){
String[] split = biaodashi.split(" ");
List<String> houzhui=new ArrayList<String>();
for (String qq : split) {
houzhui.add(qq);
}
return houzhui;
}
public static int jisuan(List<String> houzhui){
Stack<String> stack = new Stack<>();
for (String ww : houzhui) {
if(ww.matches("\\d+")){
stack.push(ww);
}
else{
int res=0;
int num2=Integer.parseInt(stack.pop());
int num1=Integer.parseInt(stack.pop());
if(ww.equals("+")){
res=num1+num2;
}
else if(ww.equals("-")){
res=num1-num2;
}
else if(ww.equals("*")){
res=num1*num2;
}
else if(ww.equals("/")){
res=num1/num2;
}
stack.push(""+res);
}
}
return Integer.parseInt(stack.pop());
}
}
代码运行效果如下: