题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1237
package D0724;
import java.util.*;
public class HDU1237 {
static Stack<String> stack1 = new Stack<String>();// 存操作符
static Stack<Double> stack2 = new Stack<Double>();// 存操作数
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str;// 接收一行输入
double result;//保存最后结果
while (sc.hasNextLine()) {
str = sc.nextLine();
if (str.equals("0"))
break;
// 初始化变量以及堆栈
result = 0;
String[] charr = str.split(" ");
for (int i = charr.length - 1; i >= 0; i--) {
String s = charr[i];
if (s.equals("+") || s.equals("-") || s.equals("*")
|| s.equals("/"))
stack1.push(s);
else
stack2.push(Double.valueOf(s));
}
// System.out.println(stack1.size()+" "+stack2.size());
while (!stack1.isEmpty()) {
String op1 = stack1.pop();
double a = stack2.pop();
double b = stack2.pop();
//判断是否有第三个操作数
double c=0;
if (!stack2.isEmpty())
c = stack2.pop();
// 如果只有一个运算符的时候直接计算a和b
if (stack1.isEmpty()) {
result = calc(result, op1, a, b);
System.out.printf("%.2f", result);
System.out.println();
} else {// 判断操作符op1和op2优先级
String op2 = stack1.pop();
if (level(op1, op2)) {
result = calc(result, op1, a, b);
//注意入栈的顺序
stack2.push(c);
stack2.push(result);
stack1.push(op2);
} else {
result = calc(result, op2, b, c);
//注意入栈的顺序
stack2.push(result);
stack2.push(a);
stack1.push(op1);
}
}
}
}
}
// 操作符比较
private static boolean level(String op1, String op2) {
if ((op2.equals("*") || op2.equals("/"))
&& (op1.equals("+") || op1.equals("-")))
return false;
return true;
}
private static double calc(double result, String op1, double a, double b) {
// System.out.println(a + op1 + b);
char op = op1.charAt(0);
switch (op) {
case '+':
result = a + b;
break;
case '-':
result = a - b;
break;
case '*':
result = a * b;
break;
case '/':
result = a / b;
break;
default:
break;
}
return result;
}
}