中缀表达式转后缀表达式并计算

中缀表达式转后缀表达式分为以下几个步骤:

1.若遇到数字或.,则直接输出;

2.若遇到(直接入栈;

3.若遇到运算符,则需将该运算符与栈顶运算符比较,若该运算符小于或等于栈顶运算符,则将栈顶运算符输出,并将该运算符压入栈(不管怎样);

4.若遇到),则将(前面的元素全部输出,并将(弹出;

5.循环上述四步。

代码实现

import java.util.EmptyStackException;
import java.util.Scanner;
import java.util.Stack;
 
public class Test {
	 private static String[] houZhui(String middle)// 中缀表达式转后缀表达式
	    {
	        String last[] = new String[middle.length()+1];
	        StringBuffer number = new StringBuffer();// 用来保存数字
	        Stack
    
    
     
      s = new Stack
     
     
      
      ();// 放运算符
	        String a;
	        s.push("#");// 起始符,栈底元素
	        int i = 0, j = 0;
	        char ch;
	        for (i = 0; i < middle.length();) {
	            ch = middle.charAt(i);
	            if (Character.isDigit(ch)){
	                while (Character.isDigit(ch))
	                {
	                    number.append(ch); 
	                    if(i
      
      
       
        1 && s.peek() != "(")
	                    last[j++] = s.pop();
	                a = String.valueOf(ch);
	                s.push(a);
	            }
	            else if(ch=='*'||ch=='/'){
	                while (s.size() > 1 && (s.peek() == "*") || s.peek() == "/")
	                    // 优先级比较,与栈顶比较
	                    last[j++] = s.pop();
	                a = String.valueOf(ch);
	                s.push(a);
	            }
	            i++;
	        }
	        while (s.size() > 1)
	            last[j++] = s.pop();
	        last[j] = "#";
	        return last;
	    }
	 
	    public static String Calculate(String middle)// 后缀表达式求值
	    {
	        String last[] = null;
	        try {
	            last = houZhui(middle);
	        } catch (EmptyStackException e) {
	        }
	        int i = 0;
	       int x1, x2, n;
	        String str;
	        Stack
       
       
        
         s = new Stack
        
        
          (); while (last[i] != "#") { str = last[i]; char ch=str.charAt(0); if(Character.isDigit(ch)){ s.push(str); } else if(ch== '+'){ x1 = Integer.parseInt(s.pop()); x2 = Integer.parseInt(s.pop()); n = x1 + x2; s.push(String.valueOf(n)); } else if(ch=='-'){ x1 =Integer.parseInt(s.pop()); x2 =Integer.parseInt(s.pop()); n = x2 - x1; s.push(String.valueOf(n)); } else if(ch=='*'){ x1 = Integer.parseInt(s.pop()); x2 = Integer.parseInt(s.pop()); n = x1 * x2; s.push(String.valueOf(n)); } else if(ch=='/'){ x1 =Integer.parseInt(s.pop()); x2 =Integer.parseInt(s.pop()); n = x2 / x1; s.push(String.valueOf(n)); } i++; } String result = s.pop(); return result; } public static void main(String args[]) { Scanner input=new Scanner(System.in); String str=input.next(); System.out.println(Calculate(str)); } } 
        
       
       
      
      
     
     
    
    


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值