因为只考虑加减乘除的运算,所以比较简单,没有特别复杂的逻辑,利用一个栈的出栈、入栈操作就可以了。
下面是具体的代码实现
import java.util.Stack;
/*
* 编写一段程序,对给定的后序表达式,求值并打印结果。
*/
/*
* 此程序因为只考虑加减乘除的操作,所以比较简单,核心就是用栈Stack的入栈,出栈来实现。
* 注意一点就是,给定的后序表达式,需要在各个数字及操作符间添加空格符号,特别是结尾处。
*
*/
public class LastExpressValue {
private static Stack<String> target=new Stack<String>();
public static void lastExpressValue(String str) {
String temp=new String();
String operator="+-*/";
double num1=0;
double num2=0;
double numresult=0;
for(int i=0; i<str.length(); i++) {
if(!str.substring(i,i+1).equals(" ")) {
temp=temp+str.substring(i,i+1);
continue;
}
else {
if(!operator.contains(temp)) {
target.push(temp)