All pastes #753158 Raw Edit

Someone

public text v1 · immutable
#753158 ·published 2007-10-29 00:13 UTC
rendered paste body
	boolean postfixExpression()
	{
		stk.clear();
		Scanner scan = new Scanner(expression);
		char current; 
		// The algorithm for doing the conversion.... Follow the bullets
		while (scan.hasNext())
		{
			String token = scan.next();
						
			if (isNumber(token)) // Bullet # 1
				postfix += token + " ";	
			else 
			{
				current = token.charAt(0);
				
				if (isParentheses(current)) // Bullet # 2 begins
				{
					if(stk.empty() || current == Constants.LEFT_NORMAL)
					{
						// push this element on the stack;
						stk.push(new Character(current));
					}
					else if (current == Constants.RIGHT_NORMAL)
					{
						try
						{
							Character ch = (Character)stk.pop();
							char top = ch.charValue();

							while (top != Constants.LEFT_NORMAL)
							{
								postfix += top + " ";
								ch = (Character)stk.pop();
								
								top = ch.charValue();	
							}
						}
						catch(EmptyStackException e)
						{
							return false;
						}
					}
				}// Bullet # 2 ends
				else if (isOperator(current))// Bullet # 3 begins
				{
					if(stk.empty())
						stk.push(new Character(current));
					else
					{
						try
						{
							char top = (Character)stk.peek();
							boolean higher = hasHigherPrecedence(top, current);
							
							while(top != Constants.LEFT_NORMAL && higher)
							{								
								postfix = postfix + stk.pop() + " ";
								top = (Character)stk.peek();
							}
							stk.push(new Character(current));
						}
						catch(EmptyStackException e)
						{
							stk.push(new Character(current));
						}
					}
				}// Bullet # 3 ends
			}
		} // Outer loop ends
		
		try
		{
			while(!stk.empty()) // Bullet # 4
			{
				postfix += stk.pop() + " ";
			}	 
		}
		catch(EmptyStackException e)
		{
			
		}
		
		return true;
	}