package stack;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
public class PolandNotation {
public static void main(String[] args) {
//表达式
String suffixExpression="3 400 + 5 * 6 -";
//思路:
//1.先放入ArrayList中
//2.传递给一个方法完成计算
List<String> cal=getListString(suffixExpression);
System.out.println(cal);
int res=calculate(cal);
System.out.println("结果为"+res);
}
public static List<String>getListString(String suffixExpression){
String[] split=suffixExpression.split(" ");
List<String> list=new ArrayList<String>();
for(String ele:split){
list.add(ele);
}
return list;
}
public static int calculate(List<String> lis){
Stack<String> stack=new Stack<String>();
for (String item:lis){
if (item.matches("\\d+")){//匹配多位数
stack.push(item);
}else {
int num2=Integer.parseInt(stack.pop());
int num1=Integer.parseInt(stack.pop());
int res=1;
switch (item){
case "+":res= num1+num2;
break;
case "-":res= num1-num2;
break;
case "*":res= num1*num2;
break;
case "/":res= num1/num2;
break;
}
stack.push(String.valueOf(res));
}
}
return Integer.parseInt(stack.pop());
}
}
逆波兰计算器
最新推荐文章于 2024-10-31 18:26:46 发布