逆波兰计算器的简单应用
逆波兰表达式的计算 (后缀表达式)
中缀表达式 :(3+4)*5-6
后缀表达式 :“3 4 + 5 * 6 -” 从左向右扫描
前缀表达式 :"- * + 3 4 5 6" 从右向左扫描
将数字入栈,有运算符的话,就从栈中pop出两个元素,计算出结果后将结果再入栈
package com.tmo.stack;
import java.util.ArrayList;
import java.util.Stack;
/**
*
* @author tmo 逆波兰表达式的计算 (后缀表达式) 中缀表达式 :(3+4)*5-6 后缀表达式 :"3 4 + 5 * 6 -" 从左向右扫描
* 前缀表达式 :"- * + 3 4 5 6" 从右向左扫描 将数字入栈,有运算符的话,就从栈中pop出两个元素,计算出结果后将结果再入栈
*/
public class NiBoLan {
public static void main(String[] args) {
// 定义一个后缀表达式
String str = "3 4 + 50 * 60 -";
// 将表达式字符串中的内容放到list中
ArrayList<String> list = getList(str);
System.out.println(list);
int i = calculate(list);
System.out.println("结果为:"+i);
}
// 将后缀表达式放入list集合
public static ArrayList<String> getList(String str) {
// 字符串切割
String[] split = str.split(" ");
// 将字符串放到list中
ArrayList<String> list = new ArrayList<String>();
for (String string : split) {
list.add(string);
}
return list;
}
// 计算
public static int calculate(ArrayList<String> list) {
// 新建栈
Stack<String> stack = new Stack<String>();
// 遍历list
for (String item : list) {
if (item.matches("\\d+")) {// 匹配多位数字
stack.push(item);
}else {
// 不是数字,为运算符
//从栈中取出两个数字,进行运算
int num2 = Integer.parseInt(stack.pop()); //先取出
int num1 = Integer.parseInt(stack.pop()); //后取出
int res = 0; //保存结果
switch (item) {
case "+":
res = num1 + num2;
break;
case "-":
res = num1 - num2;
break;
case "*":
res = num1 * num2;
break;
case "/":
res = num1 / num2;
break;
default:
System.out.println("输入字符有误");
break;
}
//将结果存入栈
stack.push(""+res);
}
}
//for循环结束后,栈中剩余的就是最终结果
return Integer.parseInt(stack.pop());
}
}