码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2015-05-13 22:02:23      阅读:127      评论:0      收藏: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;
	}



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

标签:

原文地址:http://blog.csdn.net/yj1499945/article/details/45697389

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!