help with postfix evaluator in java

stacks of double

Page 1 of 1

0 Replies - 2046 Views - Last Post: 11 November 2007 - 06:35 PM Rate Topic: -----

#1 ashley88helpme   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 11-November 07

help with postfix evaluator in java

Post icon  Posted 11 November 2007 - 06:35 PM

I was wondering if anyone could help me. I am writing code for a postfix evaluator in java using generic Double stack. We were given a token class that has a few simple methods such as isNumber(), isOperator(). I have some code written but am stuck as where to go so any help will be appreciated.

This is my code
public class PostFixEvaluator {

	public static String evaluate(String input) {
		// Only evaluates if the string contains characters.
		if (input.length() > 0) {

			StringTokenizer tokenizer = new StringTokenizer(input, " \t*/+-",
					true);

			Stack<Double> postfix = new Stack<Double>();

			try {
				while (tokenizer.hasMoreTokens()) {
					
					String nextItem = tokenizer.nextToken();
					
					if (!nextItem.equals(" ") && !nextItem.equals("\t")) {
						Token t = new Token(nextItem);
						
						if (t.isNumber()) {
							postfix.push((newDouble(t)));
						} else {
							if( t.isOperator())
							 {
								switch (t.operatorCharValue()) {
								case '+': // Addition
									if(postfix.size()>= 2){
									double x = postfix.pop().numValue();
									double y = postfix.pop().numValue();
									double newvalue = y + x;
									postfix.push(new Double(newvalue));
									}
									break;
								case '-': // Subtraction
									if(postfix.size()>=2){
									double x = postfix.pop().numValue();
									double y = postfix.pop().numValue();
									double newvalue = y - x;
									postfix.push(new Double(newvalue));
									}
									break;
								case '*': // Multiplication
									if(postfix.size()>=2){
									double x = postfix.pop().numValue();
									double y = postfix.pop().numValue();
									double newvalue = y * x;
									postfix.push(new Double(newvalue));
									}
									break;
								case '/': // Division
									if(postfix.size()>=2){
									double x = postfix.pop().numValue();
									double y = postfix.pop().numValue();
									double newvalue = y / x;
									postfix.push(new Double(newvalue));
									}
									break;
								}
							}
						}
					}
				}
			} catch (IllegalArgumentException e) {
				return e.getMessage();
			}

			return postfix.pop().numValue();
		}
	}
}																												


Is This A Good Question/Topic? 0
  • +

Page 1 of 1