Java命令行计算器(中缀表达式求值)

/**
 * 加减乘除计算器
 * 支持带括号的整数优先级运算
 * 输入一个中缀表达式,符号与数字用空格隔开,例如 ( 1 + 2 ) * 3 - 4
 * 输出运算结果
 * */
import java.util.Scanner;
import java.util.Stack;

public class Calculator{
	public static int getPriority(String op){  //获取操作符优先级
		if(op.equals("+") || op.equals("-")){
			return 1;
		}else if(op.equals("*") || op.equals("/")){
			return 2;
		}else if(op.equals("(")){   //栈外括号优先级最大,栈内最小
			return 0;
		}else if(op.equals("=")){
			return -1;
		}else
			return -1;
	}
	
	public static boolean isNum(String str){  //判断字符串是否为数字
		if(str.charAt(0) == '-'){  //处理负数
			if(str.length() == 1) {
				return false;
			}else {
				for(int i = 1; i < str.length(); i++){
					if(!Character.isDigit(str.charAt(i))){
						return false;
					}
				}
			}
		}else {
			for(int i = 0; i < str.length(); i++){
				if(!Character.isDigit(str.charAt(i))){
					return false;
				}
			}
		}		
		return true;
	}
	
	public static int operation(int a,int b,String op){  //根据运算符进行运算
		int result = 0;
		if(op.equals("+"))
			result = a + b;
		else if(op.equals("-"))
			result = a - b;
		else if(op.equals("*"))
			result = a * b;
		else if(op.equals("/"))
			result = a / b;
		return result;
	}
	
	public static void main(String[] args){
		Scanner sc = new Scanner(System.in);
		String str = sc.nextLine();
		String[] expr = str.split("\\s+");  //根据空格分割字符串
		
		Stack<Integer> opNum = new Stack<Integer>();  //数字栈
		Stack<String> opSign = new Stack<String>();  //操作符栈
		opSign.push("=");
		
		for(String s : expr){
			if(isNum(s)){  //遇到数字,直接压栈
				int num = Integer.parseInt(s);
				opNum.push(num);
			}else if(s.equals("(")){  //遇到左括号,直接压栈
				opSign.push(s);
			}
			else if(s.equals(")")){
				while(true) {
					String op = opSign.pop();
					if(op.equals("("))  //弹出左括号,结束
						break;
					else {  //不是左括号,则为操作符,进行运算
						int right = opNum.pop();
						int left = opNum.pop();
						int re = operation(left,right,op);
						opNum.push(re);
					}
				}
			}else{  //遇到的是+ - * /
				while(true){
					if(getPriority(s) > getPriority(opSign.peek())){
						opSign.push(s);  //当前符号优先级比栈顶符号优先级高,直接入栈
						break;
					}else{  
						int right = opNum.pop();
						int left = opNum.pop();
						String op = opSign.pop();
						int re = operation(left,right,op);
						opNum.push(re);
					}
				}				
			}
		}
		while(!opSign.peek().equals("=")){  //对栈中剩余数进行运算
			int right = opNum.pop();
			int left = opNum.pop();
			String op = opSign.pop();
			int re = operation(left,right,op);
			opNum.push(re);
		}
		System.out.println(opNum.pop());
	}
}
  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值