栈操作10以内四则运算

四则运算首先是要明白将中缀表达式转换为后缀表达式,如1、中缀式:(2+6)*8/3 转换为后缀式为:26+8*3/ ;2、中缀式: 2+6*8/3 转换为后缀是为:268*3/+ 

之后是通过得到的后缀表达式进行计算:遍历后缀表达式,遇到数字存入栈中,遇到操作符,就将栈中的数字弹出进行计算,将计算的结果入栈,如此循环至遍历结束,即得出结果。

代码如下:

import java.util.Stack;

public class Arithmetic {
	// 前缀转后缀
	public static String suffix(String str) {
		String suffix = "";
		Stack<Character> stack = new Stack<Character>();
		for (int i = 0; i < str.length(); i++) {
			char ch = str.charAt(i);
			if (ch >= '0' && ch <= '9') {
				suffix += str.charAt(i);
				continue;
			}
			if (ch == '(') {
				stack.push('(');
				continue;
			}
			if (ch == '/' || ch == '*') {
				while (!stack.empty() && (stack.peek().equals('/') || stack.peek().equals('*'))) {
					suffix += stack.pop();
				}
				stack.push(ch);
				continue;
			}
			if (ch == '+' || ch == '-') {
				while (!stack.empty() && (stack.peek() != '(')) {
					suffix += stack.pop();
				}
				stack.push(ch);
				continue;
			}
			if (ch == ')') {
				while (stack.peek() != '(') {
					suffix += stack.pop();
				}
				stack.pop();
			}
		}
		while (!stack.empty()) {
			suffix += stack.pop();
		}
		return suffix;
	}

	// 计算
	public static double caculate(String str) {
		String op = suffix(str);
		double result = 0;
		String range = "0123456789";
		Stack<String> stack = new Stack<String>();
		for (int i = 0; i < op.length(); i++) {
			String item = op.substring(i, i+1);
			//此处通过contains方法判断是操作符还是数字
			if (range.contains(item)) {
				stack.push(item);
			} else {
				if(item.equals("+")) {
					result = Double.parseDouble(stack.pop()) + Double.parseDouble(stack.pop());
					stack.push(String.valueOf(result));
				}
				if(item.equals("-")) {
					//注意减法和下面除法的出栈顺序
					String a = stack.pop();
					String b = stack.pop();
					result = Double.parseDouble(b) - Double.parseDouble(a);
					stack.push(String.valueOf(result));
				}
				if(item.equals("*")) {
					result = Double.parseDouble(stack.pop()) * Double.parseDouble(stack.pop());
					stack.push(String.valueOf(result));
				}
				if(item.equals("/")) {
					String a = stack.pop();
					String b = stack.pop();
					result = Double.parseDouble(b) / Double.parseDouble(a);
					stack.push(String.valueOf(result));
				}
			}
		}
		System.out.println(result);
		return result;
	}

	public static void main(String[] args) {
		new Arithmetic().caculate("(2+6)*8/3");
		new Arithmetic().caculate("2+6*8/3");
		new Arithmetic().caculate("6*7-3*6");
	}
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值