逆波兰计算器
- 输入逆波兰表达式,使用栈stack计算器结果
- 思路分析:根据题目所给的后缀表达式,从左到右,计算。遇到数字,入栈,遇到符号,栈弹出两个数运算,结果入栈,一直运算到最右边的数字
- 代码实现:
package stack;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
public class PolanNotation {
public static void main(String[] args) {
//先定义逆波兰表达式,为了方便,字符之间用空格隔开
String suffixExpression = "3 4 + 5 * 6 -";
//思路
//1、先将suffixexpression放到ArrayList中
//2、将ArrayList传递给一个方法,配合栈完成计算
//今日任务,关于集合在做复习
List<String> rpnList = getListString(suffixExpression);
//关于泛型,仅仅知道皮毛,也忘得差不多了!这是说list中的元素仅仅只能够容纳string的吗?
System.out.println("rpnList = " + rpnList);
System.out.println("计算结果为:" + calculate(rpnList));
}
//将表达式按照运算符和数据依次放到ArrayList中
public static List<String> getListString(String suffixExpression){
//将suffixExpression分割
String[] split = suffixExpression.split(" ");
List<String> list = new ArrayList<String>();
//List针对的是什么样的数据类型,又有什么作用?为什么用ArrayList?都想不起来了!!
for (String ele:split){
list.add(ele);
}
//for的加强循环for(数组元素类型 变量名:数组名){}
return list;
}
//完成对逆波兰表达式的运算
public static int calculate(List<String> list){
//创建栈,用类库里面自带的栈
Stack<String> stack = new Stack<String>();
//关于类库里面的栈也忘得差不多了,一点印象都没有,构造方法有什么样的类别也不知道
for (String ele:list){
if (ele.matches("[0-9]+")){
//问:您知道matches和equals的区别吗?为啥不能用equals
//match只能用正则表达式,equal不用正则表达式
//System.out.println(ele);
stack.push(ele);
}else{
int res = 0;
int num1 = Integer.parseInt(stack.pop());
int num2 = Integer.parseInt(stack.pop());
if(ele.equals("+")){
res = num1 + num2;
}else if(ele.equals("-")){
res = num2 - num1;
}else if(ele.equals("*")){
res = num1 * num2;
}else if(ele.equals("/")){
res = num2 / num1;
}else{
System.out.println("数据错误,无法运算");
}
stack.push("" + res);
//我认为不能把赋值语句放在句首,因为如果是错误符号,那就多出栈了两个数
}
}
int res = Integer.parseInt(stack.pop());
return res;
}
}
对比总结:
这个没什么好说的,用了很多东西,手生了,然后就都忘记了
复习补差:
集合相关知识:
泛型相关知识:
来源:CSDN
作者:~梦醒~
链接:https://blog.csdn.net/Blackoutdragon/article/details/103834339