2 Replies - 3607 Views - Last Post: 04 July 2011 - 11:32 AM Rate Topic: -----

#1 RobW1985  Icon User is offline

  • New D.I.C Head

Reputation: 14
  • View blog
  • Posts: 38
  • Joined: 22-June 11

PostFix Evaluator problems using a Stack

Posted 04 July 2011 - 09:30 AM

Hi all, new to programming and java and I am having problems with this PostFixEvaluator example from my book using a stack interface. I took an intro to programming course at school recently and enjoyed it so I have been trying to complete the rest of the book on my own but have hit a snag. I am now into the Stacks chapter. I have never used or seen stacks before this and the one example the book provides is not working. I don't have any compile-time or run-time errors so it seems to be a logic issue. When I run the file with the main method it throws the IOException and never computes the expression. I have entered simple expressions like 47- and it throws the exception. If I enter 47 without an operator it returns 0 and continues processing. I am unable to trace why I am getting this exception. I have the source code from the book and when I compile and run the source code I am getting the same results. The program is supposed to just solve a postfix expression provided by the user. Can anyone shed some light on this? Here is my code for the files.

Stack :
package Chapter14;

public interface Stack<T> {

	// Adds the specified element to the top of the stack
	public void push(T element);
	// Removes and returns the top element from the stack
	public T pop();
	// Returns a reference to the top element of this stack without removing it
	public T peek();
	// Returns true if the stack contains no elements and false otherwise
	public boolean isEmpty();
	// Returns the number of elements in a stack
	public int size();
	// Returns a string representation of the stack
	public String toString();
}




LinearNode :
package Chapter14;

public class LinearNode<T> {

	private LinearNode<T> next;
	private T element;
	
	// Creates an empty node
	public LinearNode() {
		next = null;
		element = null;
	}
	// Creates a node storing the specified element
	public LinearNode(T elem) {
		next = null;
		element = elem;
	}
	// Returns the node that follows this one
	public LinearNode<T> getNext() {
		return next;
	}
	// Sets the node that follows this one
	public void setNext (LinearNode<T> node) {
		next = node;
	}
	// Returns the element stored in this node
	public T getElement() {
		return element;
	}
	// Sets the element stored in this node
	public void setElement(T elem) {
		element = elem;
	}
}



LinkedStack :
package Chapter14;

import java.util.EmptyStackException;
import java.util.Iterator;


public class LinkedStack<T> implements Stack<T> {

	private int count;
	private LinearNode<T> top;
	
	// Creates an empty stack using the default capacity
	public LinkedStack() {
		count = 0;
		top = null;
	}
	
	public void push(T element) {
		LinearNode<T> newNode = new LinearNode<T>(element);
		newNode.setNext(top);
		top = newNode;
		count++;
	}
	// Removes the element at the top of this stack and returns a reference to it.  Throws an EmptyStackException if the stack 
	// contains no elements
	public T pop() throws EmptyStackException {
		if (count == 0) 
			throw new EmptyStackException();
		T result = top.getElement();
		top = top.getNext();
		count--;
		return result;
	}
	public T peek() throws EmptyStackException {
		if (isEmpty())
			throw new EmptyStackException();
		return top.getElement();
	}
	public boolean isEmpty() {
			return (count == 0);
	}
	public int size() {
		return count;
	}
	public String toString() {
		String result = "<Top of Stack>\n";
		LinearNode<T> current = top;
		while (current != null) {
			result += current.getElement() + "\n";
			current = current.getNext();
		}
		return result + "<Bottom of Stack>"; 
	}
}



PostFixEvaluator :
package Chapter14;

import java.util.StringTokenizer;
import Chapter14.LinkedStack;


public class PostFixEvaluator {
	
	private final char ADD = '+', SUBTRACT = '-';
	private final char MULTIPLY = '*', DIVIDE = '/';
	private LinkedStack<Integer> stack;

	// Sets up the evaluator by creating a new stack
	public PostFixEvaluator() {
		stack = new LinkedStack<Integer>();
	}
	// Evaluate the specified postfix expression.  If an operand is encountered, it is pushed onto the stack.  If an 
	// operator is encountered, two operators are popped , the operation is evaluated, and the result
	// is pushed back onto the stack
	public int evaluate(String str) {
		int op1, op2, result = 0;
		String token;
		StringTokenizer tokenizer = new StringTokenizer(str);
		while (tokenizer.hasMoreTokens()) {
			token = tokenizer.nextToken();
			if (isOperator(token)) {
				op2 = (stack.pop()).intValue();
				op1 = (stack.pop()).intValue();
				result = evalSingleOp (token.charAt(0), op1, op2);
				stack.push(result);
			} else 
				stack.push(Integer.parseInt(token));
		}
		return result;
	}
	// Determine if the specified token is an operator
	private boolean isOperator(String token) {
		return (token.equals("+") || token.equals("-") || token.equals("*") || token.equals("/"));
	}
	// Performs integer evaluation on a single expression consisting of the specified operator and operands
	private int evalSingleOp(char operation, int op1, int op2) {
		int result = 0;
		
		switch(operation) {
		case ADD:
			result = op1 + op2;
			break;
		case SUBTRACT:
			result = op1 - op2;
			break;
		case MULTIPLY:
			result = op1 * op2;
			break;
		case DIVIDE:
			result = op1 / op2;
		}
		return result;
	}
	
}




PostFix :
package Chapter14;

import java.util.Scanner;

public class Postfix {
	
	public static void main (String[] args) {
		
		String expression, again;
		int result;
		
		try {
			Scanner scan = new Scanner (System.in);
			do {
				PostFixEvaluator evaluator = new PostFixEvaluator();
				System.out.println("Enter a valid postfix expression.");
				expression = scan.nextLine();
				
				result = evaluator.evaluate(expression);
				System.out.println();
				System.out.println("The result of your expression is : "+result);
				
				System.out.println("Evaluate another expression [Y/N] ?");
				again = scan.nextLine();
				System.out.println();
				
			} while (again.equalsIgnoreCase("y"));
			
		} catch (Exception IOException) {
			System.out.println("Input exception reported.");
		}
	}

}



Is This A Good Question/Topic? 0
  • +

Replies To: PostFix Evaluator problems using a Stack

#2 RobW1985  Icon User is offline

  • New D.I.C Head

Reputation: 14
  • View blog
  • Posts: 38
  • Joined: 22-June 11

Re: PostFix Evaluator problems using a Stack

Posted 04 July 2011 - 09:48 AM

ok just tried something, not sure if this will even help me or not. I created an IOException object and assigned it to a variable in the PostFix file. I then called the getMessage() method on the variable to see if it would maybe show where the problem was coming from and all it did was display null in the console. Not sure if this would help but it was one of few ideas left in my head
Was This Post Helpful? 0
  • +
  • -

#3 RobW1985  Icon User is offline

  • New D.I.C Head

Reputation: 14
  • View blog
  • Posts: 38
  • Joined: 22-June 11

Re: PostFix Evaluator problems using a Stack

Posted 04 July 2011 - 11:32 AM

lol, holy crap I just figured it out, I'm an idiot. This is also my first time using a StringTokenizer and I realized the problem was the way I was inputting the strings. When I read the documentation on the StringTokenizer I realized the tokenizer separates the string by the default delimiters which is a space, when I entered strings I entered them like this, 47-3*, what I should have done was enter them like this, 4 7 - 3 *, when entered the second way the program works.

This post has been edited by RobW1985: 04 July 2011 - 11:32 AM

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1