代码实现:实现的一些自己的思路总结:
可以直接使用java中的栈Stack stack=new Stack();
表达式直接使用String suffixexpression=“3 4 * 6 /”;这种格式的后缀表达式,
- 把表达式放入ArrayList集合中操作,用空格隔开
- 使用一个方法来计算表达式,直接使用item.matches();正则表达式来匹配一。
- 整型变成字符串 数字加上一个 " "空字符就好
package com.demo;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
public class calculate {
public static void main(String[] args) {
//定义后缀表达式
//(3+4)*5-6=>3 4 +5*6-
String suffixExpression = "3 48 + 5 * 6 -";
//放入ArrayList,传入一个方法,配合栈然后,然后完成计算器
List<String> rpnList = getListString( suffixExpression );
System.out.println( rpnList );
int result=calculate( rpnList );
System.out.println( result);
}
// 逆波兰表达式,依次将数据扣运算符放入到ArrayList中
public static List<String> getListString(String suffixExpression) {
//将suffixExpression分割
String[] strings=suffixExpression.split( " " );
List<String> list=new ArrayList<String>();
for (String ele:strings
) {
list.add( ele );
}
return list;
}
// 完成对后缀表达式的计算
/*(3+4)*5-6
*1. 从左至右扫描,将3和4压入栈
* 2. 遇到运算符弹出3和4,计算3和4的运算,并且将提到的7重新压入栈中
* 3.将5入栈
* 4.遇到运算符重复2步骤
* 5. 然后将数字(又入栈)
* 6. 计算出35-6的值,从而得出结果。
*
*
*
*
*
* */
public static int calculate(List<String> ls) {
// 创建栈
Stack<String> stack = new Stack<String>();
for (String item : ls) {
//这里使用正则表达式来取出数把碰到的所有的数据进入栈中
if (item.matches( "\\d+" )) {//匹配多位数
// 入栈
stack.push( item );
} else {
// pop出两个数,并运算再入栈
/*Exception in thread "main" java.lang.NumberFormatException:
For input string: " 7"
trim()去除空格的函数,如果没有去除报上面的异常
*/
int num2 = Integer.parseInt( stack.pop().trim() );
int num1 = Integer.parseInt( stack.pop().trim() );
int result = 0;
if (item.equals( "+" )) {
result = num1 + num2;
} else if (item.equals( "-" )) {
result = num1 - num2;
} else if (item.equals( "*" )) {
result = num1 *num2;
} else if (item.equals( "/" )) {
result = num1 / num2;
} else {
throw new RuntimeException( "运算符异常" );
}
//把res入栈 加上空格变成字符
stack.push( " "+result );
}
}
//最后留在栈中的运算结果 把字符格式转化为整形的格式
return Integer.parseInt( stack.pop().trim() );
}
}