`

解析算术表达式

阅读更多

下面的是一个比较简单的情况,很多情况都没考虑,比如不是数字(如字母等),比如是多位数的运算(如23+456)等。

 

public class SuffixCompute 
{
	private static String suffix = "";
	
	public static void main(String[] args)
	{
		Stack<String> stack = new Stack<String>();
		
		String str = "(2+3)*4-6/3";
		
		System.out.println("The expession to compute is : " + str);
		
		Compute(str, stack);
	}
	
	public static void Compute(String expression, Stack<String> stack)
	{
		char ch;
		int num1 = 0;
		int num2 = 0;
		int result = 0;
		String str = "";
		
		str = changeToSuffix(expression, stack);
		
		for(int i=0; i<str.length(); i++)
		{
			ch = str.charAt(i);
			
			if(ch > '0' && ch < '9')
				stack.push(String.valueOf(ch));
			else
			{
				num1 = Integer.parseInt(stack.pop());
				num2 = Integer.parseInt(stack.pop());
				
				switch(ch)
				{
					case '+':
						result = num2 + num1;
						break;
						
					case '-':
						result = num2 - num1;
						break;
						
					case '*':
						result = num2 * num1;
						break;
						
					case '/':
						result = num2 / num1;
						break;
				}
				
				stack.push(String.valueOf(result));
			}
		}
		
		result = Integer.parseInt(stack.pop());
		
		System.out. println("The result is : " + result);
	}
	
	public static String changeToSuffix(String str, Stack<String> stack)
	{
		char ch;
		
		for(int i=0; i<str.length(); i++)
		{
			ch = str.charAt(i);
			
			switch(ch)
			{
				case '+':
				case '-':
					getOper(ch, 1, stack);
					break;
					
				case '*':
				case '/':
					getOper(ch, 2, stack);
					break;
					
				case '(':
					stack.push(String.valueOf(ch));
					break;
					
				case ')':
					getParen(ch, stack);
					break;
					
				default:
					suffix += ch;
					break;
			}
		}
		
		while(!stack.isEmpty())
		{
			suffix += stack.pop();
		}
		
		System.out.println("The suffix is :" + suffix);
		
		return suffix;
	}
	
	public static void getOper(char ch, int flag1, Stack<String> stack)
	{
		char oper;
		int flag2;
		
		while(!stack.isEmpty())
		{
			oper = stack.pop().charAt(0);
			
			if(oper == '(')
			{
				stack.push(String.valueOf(oper));
				break;
			}
			else
			{
				if(oper == '+' || oper == '-')
					flag2 = 1;
				else
					flag2= 2;
				
				if(flag2 < flag1)
				{
					stack.push(String.valueOf(oper));
					break;
				}
				else
				{
					suffix += oper;
				}
			}
		}
		stack.push(String.valueOf(ch));
	}
	
	public static void getParen(char ch, Stack<String> stack)
	{
		char temp;
		
		while(!stack.isEmpty())
		{
			temp = stack.pop().charAt(0);
			
			if(temp == '(')
				break;
			else
				suffix += temp;
		}
	}
}

 

 

输出如下:

The expession to compute is : (2+3)*4-6/3
The suffix is :23+4*63/-
The result is : 18

 

1
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics