HDU1237(堆栈应用)

题目链接: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;
	}

}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

怎么演

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值