逆波兰计算器实现1.0版
作者:互联网
说明:(3+4)*5-6的逆波兰数是"30 4 + 5 * 6 -",然后对其逆波兰数进行计算
项目地址:
java数据结构与算法: 自己学习与练习数据结构的仓库https://gitee.com/ALi_L/javaDataStructurs.git
1.用getListString()方法将"30 4 + 5 * 6 -"按照空格切分。
/**
* create by: ALi
* description: 分隔字符串
* create time: 2021/11/4 20:10
* @Param: null
* @return list型
*/
public static List<String> getListString(String str){
String[] split = str.split(" ");
List<String> list = new ArrayList<String>();
for (String item:split){
list.add(item);
}
return list;
}
2.Calculator()方法进行计算。注意:减法和除法的前后顺序。
public static int Calculator(List<String> list){
//创建一个栈
Stack<String> stack = new Stack();
int num1 = 0;
int num2 = 0;
int res = 0;
for (String item : list)
if (item.matches("\\d+")) {
stack.push(item);
} else {
num2 = Integer.parseInt(stack.pop());
num1 = Integer.parseInt(stack.pop());
if ("-".equals(item)) {
res = num1 - num2;
} else if ("+".equals(item)) {
res = num1 + num2;
} else if ("*".equals(item)) {
res = num1 * num2;
} else if ("/".equals(item)) {
res = num1 / num2;
} else {
num1 = 0;
num2 = 0;
throw new RuntimeException("计算错误");
}
//将结果放入栈中
stack.push(""+res);
}
return Integer.parseInt(stack.pop());
}
代码如下:
package DataStructures.Stack;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
/**
* @author :ALi
* @date :Created in 2021/11/4 19:21
* @description:逆波兰计算器
* @modified By:
* @version: $
*/
public class PolandNotation {
public static void main(String[] args){
//逆波兰计算器:(3+4)*5-6 => 3 4 + 5 * 6 -
String str = "30 4 + 5 * 6 -";
List<String> rpnList = getListString(str);
int res = Calculator(rpnList);
System.out.println(res);
}
/**
* create by: ALi
* description: 分隔字符串
* create time: 2021/11/4 20:10
* @Param: null
* @return list型
*/
public static List<String> getListString(String str){
String[] split = str.split(" ");
List<String> list = new ArrayList<String>();
for (String item:split){
list.add(item);
}
return list;
}
public static int Calculator(List<String> list){
//创建一个栈
Stack<String> stack = new Stack();
int num1 = 0;
int num2 = 0;
int res = 0;
for (String item : list)
if (item.matches("\\d+")) {
stack.push(item);
} else {
num2 = Integer.parseInt(stack.pop());
num1 = Integer.parseInt(stack.pop());
if ("-".equals(item)) {
res = num1 - num2;
} else if ("+".equals(item)) {
res = num1 + num2;
} else if ("*".equals(item)) {
res = num1 * num2;
} else if ("/".equals(item)) {
res = num1 / num2;
} else {
num1 = 0;
num2 = 0;
throw new RuntimeException("计算错误");
}
//将结果放入栈中
stack.push(""+res);
}
return Integer.parseInt(stack.pop());
}
}
标签:1.0,num1,num2,res,list,item,波兰,计算器,stack 来源: https://blog.csdn.net/weixin_56640241/article/details/121150508