java写的专门对付运算式子的方法

7 篇文章 0 订阅

就是把昨天写的写成了爪哇,少了一些功能,基本的在,牛逼的大牛可以拿去修改做的更好。

	public  boolean judge(char ch)//判断是不是字符数字
	{
		if(ch >= '0' && ch <= '9')
		{
			return true;
		}
		return false;
	}
	
	public  String[] tochange(String s_1)//中缀表达式转换为后缀表达式
	{
        String S[] = new String[1000];
        StringBuffer numBuffer = new StringBuffer();
        Stack<String> s = new Stack<String>();
        int i = 0, j = 0;
        char ch;
        while(i != s_1.length())
        {
        	ch = s_1.charAt(i);
        	if(ch >= '0' && ch <= '9')
        	{
                while (judge(ch))
                {
                    numBuffer.append(ch);
                    ch = s_1.charAt(++i);
                }
                S[j++] = numBuffer.toString();
                numBuffer = new StringBuffer(); 
                continue; 
        	}
        	else if(ch == '(')
        	{
        		s.push("(");
        	}
        	else if(ch == ')')
        	{
        		while(s.peek() != "(")
        		{
        			S[j++] = s.pop();
        		}
        		s.pop();
        	}
        	else if(ch == '+' || ch == '-')
        	{
        		while(s.size() != 0 && s.peek() != "(")
        		{
        			S[j++] = s.pop();
        		}
        		
        		s.push(String.valueOf(ch));
        	}
        	else if(ch == '*' || ch == '/')
        	{
        		while(s.size() != 0 && (s.peek()== "*" || s.peek() == "/"))
        		{
        			S[j++] = s.pop();
        		}
        		s.push(String.valueOf(ch));
        	}
        	i++;
        }
        
        while (s.size() != 0)
            S[j++] = s.pop();
        S[j] = "=";
        
    	return S;
	}
	
	public int add(String s_1)//进行计算
	{
		String []sn = tochange(s_1);
		Stack<String>s = new Stack<String>();
		int i = 0,n = 0,m = 0,x = 0;
		char ch;
		while(sn[i] != "=")
		{
			ch = sn[i].charAt(0);
			if(ch >= '0' && ch <= '9')
			{
				s.push(String.valueOf(sn[i]));
			}
			else if(ch == '+')
			{
			    n = Integer.parseInt(s.pop());
				m = Integer.parseInt(s.pop());
			    x = n + m;
				s.push(String.valueOf(x));
			}
			else if(ch == '-')
			{
				n = Integer.parseInt(s.pop());
				m = Integer.parseInt(s.pop());
				x = m - n;
				s.push(String.valueOf(x));
			}
			else if(ch == '*')
			{
				n = Integer.parseInt(s.pop());
				m = Integer.parseInt(s.pop());
				x = m * n;
				s.push(String.valueOf(x));
			}
			else if(ch == '/')
			{
				n = Integer.parseInt(s.pop());
				m = Integer.parseInt(s.pop());
				x = m / n;
				s.push(String.valueOf(x));
			}
			i++;
		}
		String ss = s.pop();
		int number = Integer.parseInt(ss);
		return number;
	}



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值