PositifixExpression类
import java.util.Stack;
/*
后缀表达式求值
*/
public class PostfixExpression extends Thread{
public static void main(String args[]) {
String inputStr = ""; //后缀表达式字符串
Stack<Double> st = new Stack<Double>(); //栈
String numStr = ""; //存储拼接后的数字字符串
double num = 0; //拼接后的数字
inputStr = ReaderAndWrite.read();
for(int i = 0;i < inputStr.length();i++) {
if(inputStr.charAt(i) == '.'){ //遇到.即数字已经提取完成,开始入栈,注意置空原来的字符串
num = Double.parseDouble(numStr);
System.out.println(num);
st.push(num);
numStr = "";
continue;
}else if(inputStr.charAt(i) >= '0' && inputStr.charAt(i) <= '9'){ //遇到数字,进行追加到字符串中存取
numStr += inputStr.charAt(i);
}else if(inputStr.charAt(i) == '+' || inputStr.charAt(i) == '/' || inputStr.charAt(i) == '*' || inputStr.charAt(i) == '-'){
operation(inputStr.charAt(i),st);
}
}
System.out.println(st.pop());
}
public static void operation(char c,Stack<Double> st) {
int size = st.size();
double opB = st.pop();
double opA = st.pop();
double result = 0;
switch (c){
case '+':
result = opA + opB;
break;
case '-':
result = opA - opB;
break;
case '*':
result = opA * opB;
break;
case '/':
result = opA / opB;
break;
default:
break;
}
st.push(result);
}
}
ReadAndWrite类
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class ReaderAndWrite {
public static String read() {
InputStreamReader ir = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(ir);
String inputStr = "";
try {
inputStr = in.readLine();
}catch(IOException e) {
e.printStackTrace();
}
return inputStr;
}
}