代码(版本二)
package cn.edut.test_stack;
import java.util.Stack;
import org.junit.Test;
public class Demo02_postfix {
@Test
public void test01() {
System.out.println("Test1:后缀求值");
String s = "6 5 2 3 + 8 * + 3 + * 2 /";
System.out.println(postfix_2(s));
}
public static int postfix_2(String input){
String[] tempString = input.split("\\s+");
Stack<Integer> stack_Integer = new Stack<>();
for(String s : tempString) {
int temp = 0 ;
switch(s) {
case "+" :
int b1 = stack_Integer.pop() ;
int a1 = stack_Integer.pop() ;
temp = a1+b1 ;
break;
case "-" :
int b2 = stack_Integer.pop() ;
int a2 = stack_Integer.pop() ;
temp = a2-b2 ;
break;
case "*" :
int b3 = stack_Integer.pop() ;
int a3 = stack_Integer.pop() ;
temp = a3*b3 ;
break;
case "/" :
int b4 = stack_Integer.pop() ;
int a4 = stack_Integer.pop() ;
temp = a4/b4 ;
break;
default: temp = Integer.parseInt(s);
}
stack_Integer.push(temp) ;
}
if(stack_Integer.size()==1) {
return stack_Integer.pop() ;
}else {
throw new IllegalAccessError();
}
}
}
代码(版本三)
package cn.edut.clac;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
import org.junit.Test;
public class Calculator_Demo {
@Test
public void Test01() {
String suffix_expression = "1 2 3 * + 4 5 + 6 * + 7 - 2 /";
System.out.println(parseExpression(suffix_expression).toString());
System.out.println(doCalc(parseExpression(suffix_expression)));;
}
@Test
public void Test02() {
}
private List<String> parseExpression(String str){
String[] strTemp = str.split("\\s+");
List<String> outList = new ArrayList<>();
for(String s : strTemp) {
outList.add(s) ;
}
return outList;
}
private int doCalc(List<String> str) {
Stack<Integer> stackInteger = new Stack<>();
for(String s : str) {
if(s.matches("\\d")) {
stackInteger.push(Integer.parseInt(s));
}
else {
int num2 = stackInteger.pop();
int num1 = stackInteger.pop();
int result = 0 ;
switch(s) {
case "+" : result = num1+num2; break;
case "-" : result = num1-num2; break;
case "*" : result = num1*num2; break;
case "/" : result = num1/num2; break;
default : throw new RuntimeException("四则运算符号对不上");
}
stackInteger.push(result) ;
}
}
return stackInteger.pop();
}
}