计算算术表达式

import java.util.Stack;

//计算中缀表达式
//1+2*(3-4)+5
public class Test1 {
/**
 * 后缀表达式计算
 * @param expstr
 * @return
 */

 public static String toPostfix(String expstr){
  String postfix="";
  
  Stack<String> stack = new Stack<String>();
  int i=0;
  int explength=expstr.length();//字符串的长度
  while (i<explength) {
   char ch = expstr.charAt(i);
   switch (ch) {
   case '+':
   case '-':
    while (!stack.empty()&&!stack.peek().equals("(")) {
     postfix+=stack.pop();
     //如果栈非空,并且栈的栈顶不是“左括号”,也就是栈顶优先级>=该操作符的优先级出栈,添加到后缀表达式中
    }
    stack.push(ch+"");//将该操作符入栈
    i++;
    break;
   case '*':
   case '/':
    while (!stack.empty()&&(stack.peek().equals("*")||stack.peek().equals("/"))) {
     postfix+=stack.pop();
    }
    stack.push(ch+"");
    i++;
    break;
   case '(':
    stack.push("(");//左括号直接入栈
    i++;
    break;
   case ')':
    String out = stack.pop();//右括号出栈
    while (out!=null&&!out.equals("(")) {
     //如果出的不是null,并且不是左括号
     postfix+=out;//添加到后缀表达式
     out=stack.pop();
    }
    i++;
    break;
   default:
    while (i<explength&&ch>='0'&&ch<='9') {
     postfix+=ch;
     i++;
     if (i<explength) {
      ch=expstr.charAt(i);
     }
    }
    postfix+=" "; //以空格为分隔符
   }
  }
  while (!stack.empty()) {
   postfix+=stack.pop();
  }
  return postfix;
 }
 
 //计算后缀表达式
 public static int value(String postfix){
  int result=0;
  int len = postfix.length();
  Stack<Integer> stack = new Stack<Integer>();
  int i=0;
  while (i<len) {
   char ch = postfix.charAt(i);
   if (ch>='0'&&ch<='9') {
    result = 0;
    while (ch!=' ') {//上面的后缀表达式以空格为分隔符
     result = result*10+Integer.parseInt(ch+"");
     //如果不是空格的话,就计算该数。比如 123 456 +。
     i++;
     ch=postfix.charAt(i);
    }//
    i++;
    stack.push(result);//将操作数压栈
   }else{
    int y = stack.pop().intValue();
    int x = stack.pop().intValue();
    switch (ch) {
    case '+':
     result = x+y ;
     break;
    case '-':
     result = x-y ;
     break;
    case '*':
     result = x*y ;
     break;
    case '/':
     result = x/y ;
     break;
    }
    stack.push(new Integer(result));
    i++;
   }
  }
  return stack.pop().intValue();
 }

}

 

 

 

 

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值