Where to Place Try/Catch Statement in Postfix Expression Evaluation?

  • Thread starter Thread starter muna580
  • Start date Start date
  • Tags Tags
    Confusion
Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
4 replies · 2K views
muna580
I am evaluating a postfix expression using stacks and stuff. Below is the method I made. But I am not sure where to put the try/catch satement and what is it that i have to catch.

Code:
	public int evaluateRPN()
	{
		StringTokenizer token = StringTokenizer(postfix);
		stk.clear();
		
		try
		{
			while(token.hasMoreTokens())
			{
				String s = token.nextToken();
				
				if(isNumber(s))
					stk.push(new Integer(Integer.parseInt(s)));
				else
				{
					char operator = s.charAt(0);
					int x1 = ((Integer)stk.pop()).valueOf();
					int x2 = ((Integer)stk.pop()).valueOf();
					
					int x3; 
					
					switch(operator)
					{
						case StackConstants.ADDITION_OPERATOR:
							x3 = x2 + x1;
							stk.push(new Integer(x3));
						break; 
						
						case StackConstants.SUBTRACTION_OPERATOR:
							x3 = x2 - x1;
							stk.push(new Integer(x3));
						break; 
						
						case StackConstants.MULTIPLICATION_OPERATOR:
							x3 = x2 * x1;
							stk.push(new Integer(x3));
						break; 
						
						case StackConstants.DIVISION_OPERATOR:
							x3 = x2 / x1;
							stk.push(new Integer(x3));
						break; 
											
						case StackConstants.MODULUS_OPERATOR:
							x3 = x2 % x1;
							stk.push(new Integer(x3));
						break; 
					}
				}
			}
		}
		catch(EmptyStackException e)
		{
			
		}
		
		return ((Integer)stk.pop()).valueOf(); 
	}
 
Physics news on Phys.org
You should put the try/catch around the Integer.parseInt() call. It will throw a NumberFormatException if the string you are trying to parse into an integer is not an integer, like the string "abc."
 
I don't think so, that parseInt() is only when isNumber(). I think the try/catch should catch malformed sequences like '2+' (and I'm not saying where that is because I imagine this is homework).
 
Oh, silly me, there is already a try/catch around almost the entire thing. The only place left is the return statement (which will error on empty stack). Stupid question. Although, if you want to catch malformed sequences you can still do that.
 
Last edited:
Having thought about this more, I realize that malformed sequences will always result in an empty stack because the stack only ever contains numbers. I had in mind a stack containing the complete expression, whereas this one only contains intermediate results.