07 使用栈计算表达式

1 计算以下表达式的值

1+((8-6)/2)+(9-4)*3


import java.util.Stack;

public class MyCalculate
{
	// 这是数字栈
	Stack<Integer> digitStack = new Stack<Integer>();
	// 这是符号栈
	Stack<String> charStack = new Stack<String>();

	public Integer getResult(String[] ss)
	{
		for (int i = 0; i < ss.length; i++)
		{
			String c = ss[i];
			if(c.matches("\\d+"))
			{
				// 表明是一个数
				this.digitStack.push(Integer.parseInt(c));
			}
			else if("(".equals(c))
			{
				this.charStack.push(c);
			}
			else if(")".equals(c))
			{

				do
				{
					Integer b = this.digitStack.pop();
					Integer a = this.digitStack.pop();
					String calChar = this.charStack.pop();
					this.digitStack.push(this.calcTwoNum(a, b, calChar));

				}
				while (!"(".equals(this.charStack.peek()));
				this.charStack.pop();
			}
			else
			{
				while (!this.charStack.isEmpty())
				{
					if(judgePriority(c, this.charStack.peek()))
					{
						break;
					}
					else
					{
						Integer b = this.digitStack.pop();
						Integer a = this.digitStack.pop();
						String calChar = this.charStack.pop();
						this.digitStack.push(this.calcTwoNum(a, b, calChar));

					}

				}
				this.charStack.push(c);
			}
		}
		
		while (!this.charStack.isEmpty())
		{
				Integer b = this.digitStack.pop();
				Integer a = this.digitStack.pop();
				String calChar = this.charStack.pop();
				this.digitStack.push(this.calcTwoNum(a, b, calChar));
		}
		
		return this.digitStack.pop();
	}

	/**
	 * 判断两个符号的优先级,如果a>b ,返回true;否则,返回false;
	 * 
	 * @param a
	 * @param b
	 * @return
	 */
	public boolean judgePriority(String a, String b)
	{
		boolean result = false;
		
		if("(".equals(b))
		{
			return true;
		}
		
		if("-".equals(b) || "+".equals(b))
		{
			if("*".equals(a) || "/".equals(a))
			{
				result = true;
			}
		}
		return result;

	}

	/**
	 * 计算两个数,注意减法与除法
	 * 
	 * @param a
	 * @param b
	 * @param calChar
	 * @return
	 */
	public Integer calcTwoNum(Integer a, Integer b, String calChar)
	{

		int result = 0;

		if("+".equals(calChar))
		{
			result = a + b;
		}
		else if("-".equals(calChar))
		{
			result = a - b;
		}
		else if("*".equals(calChar))
		{
			result = a * b;
		}
		else if("/".equals(calChar))
		{
			result = a / b;
		}

		return result;
	}

	public static void main(String[] args)
	{
		MyCalculate mc = new MyCalculate();
		//把表达式替换成下面只是为了更容易切割进行计算
		String str = "1;+;(;(;8;-;6;);/;2;);+;(;9;-;4;);*;3;";
		int result = mc.getResult(str.split(";"));
		System.out.println(result);
			
	}
}
发布了358 篇原创文章 · 获赞 0 · 访问量 2768

猜你喜欢

转载自blog.csdn.net/langli204910/article/details/105130280