JAVA 算术运算

本文介绍了一种使用栈数据结构实现的表达式求值算法,该算法能够解析并计算包含括号、加减乘除运算符及整数的数学表达式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


class GenericStack {
  private java.util.ArrayList list=new java.util.ArrayList();
 
  public int getSize(){
   return list.size();
  }
 
  public E peek(){
  
   return list.get(getSize()-1);
  }
 
  public void push(E o){
   list.add(o);
  }
  public E pop(){
   E  o=list.get(getSize()-1);
   list.remove(getSize()-1);
   return o;
  }
 
  public boolean isEmpty()
  {
   return list.isEmpty();
  }
}
public class EvaluateExpression{
    public static void main(String[] args){
    String expression="(3-2)*6+9/3";  
      try{
       System.out.println(expression+"="+evaluateexpression_r(expression));
   }catch(Exception ex){
     System.out.println("wrong expression!");
    }
    }
   
   
    public static int evaluateexpression_r(String expression){
    
      GenericStackoperandStack=new GenericStack();
  
   GenericStackoperatiorStack=new GenericStack();
  
   java.util.StringTokenizer tokens=new java.util.StringTokenizer(expression,"()+-/*",true);
   while(tokens.hasMoreTokens())
   {
      String token=tokens.nextToken().trim();
     // System.out.println(token);
   if(token.length()==0){
   continue;
   }
   else if(token.charAt(0)=='+'||token.charAt(0)=='-'){
     while(!operatiorStack.isEmpty() &&(operatiorStack.peek()=='+'||
     operatiorStack.peek()=='-'||
     operatiorStack.peek()=='*'||
     operatiorStack.peek()=='/'))
     {
      processAnOperator(operandStack,operatiorStack);
     }
     operatiorStack.push(token.charAt(0));
   }
   else if(token.charAt(0)=='*'|| token.charAt(0)=='/'){
     while(!operatiorStack.isEmpty() &&(
     operatiorStack.peek()=='*'||
     operatiorStack.peek()=='/')){
      processAnOperator(operandStack,operatiorStack);
     }
     operatiorStack.push(token.charAt(0));
   }
   else if(token.trim().charAt(0)=='('){
    operatiorStack.push('(');
   }
    else if(token.trim().charAt(0)==')'){
      while(operatiorStack.peek()!='('){
      processAnOperator(operandStack,operatiorStack);
      }
      operatiorStack.pop();
   }
   else{
    operandStack.push(new Integer(token));
   }
   }
  
   while(!operatiorStack.isEmpty()){
     processAnOperator(operandStack,operatiorStack);
   }
   return operandStack.pop();
    }
   
    public static void processAnOperator(GenericStack operandStack,GenericStackoperatiorStack){
       char op=operatiorStack.pop();
    int op1=operandStack.pop();
    int op2=operandStack.pop();
    if(op=='+')
    operandStack.push(op2+op1);
    if(op=='-')
    operandStack.push(op2-op1);
    if(op=='*')
    operandStack.push(op2*op1);
    if(op=='/')
    operandStack.push(op2/op1);
    }
 }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值