1 Replies - 7038 Views - Last Post: 21 February 2010 - 09:27 PM Rate Topic: -----

#1 Hellreaver  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 15
  • Joined: 07-February 10

Creating a Reverse Polish Notation Calculator Using Only Arrays/Stacks

Posted 21 February 2010 - 08:42 PM

As the title suggests, I need to create a reverse polish notation calculator using Java. I know how to do this using Perl, but am still getting on track learning Java. I'll show you what I have so far:

import java.util.Stack;
import java.io.*;
import java.util.*;

public class IntegerStack implements IntegerStackInterface

	{
		  private static final boolean DEBUG = false;
		  // file name containing calculation
		  private String fileName;

		  /* 
		   * Initializes file name. 
		   */
		  public void RPN(String fileName)
		  {
		    this.fileName = fileName;
		  }

		  /*
		   * Reads characters from file and stores counts.
		   */
		  private void read()
		  {
		    try
		    {
		      BufferedReader input = new BufferedReader(new FileReader(this.fileName));

		      String line = input.readLine();
		      if (line == null)
		      {
		        System.err.println("RPN, error:  file " + fileName + " is empty.");
		      }
		      else
		      {
		        do
		        {
		          String[] tokens = line.split("\\s+");
		          Integer answer = this.parseTokens(tokens);
		          if (answer != null)
		            System.out.println("answer = " + answer);
		          line = input.readLine();
		        }
		        while (line != null);
		      }

		    } // end of try
		    catch(FileNotFoundException noFile)
		    {
		      System.err.println("RPN, error:  could not open " + fileName + ".");
		      System.err.println("             File must be in same directory.");
		      System.err.println("             exiting.");
		      System.exit(-1);
		    }
		    catch(IOException ioProb)
		    {
		      System.err.println("RPN, error:  problem reading from file " + fileName + ".");
		      System.err.println("             exiting.");
		      System.exit(-1);
		    }
		  }
		  private Integer parseTokens(String[] tokens)
		  {
		    IntegerStackInterface stack = new IntegerStack();

		    for(int i = 0; i < tokens.length; i++)
		    {
		      Integer number;
		      if (tokens[i].length()== 0)
		        continue;
		      else if (this.isOperator(tokens[i]))
		      {
		        boolean success = this.calculate(stack, tokens[i]);
		        if (!success)
		          return null;
		      }
		      else if ((number = this.isNumber(tokens[i])) != null)
		        stack.push(number);
		      // Expression-ERROR 1
		      else
		      {
		        System.err.println("RPN, error:  token " + tokens[i] + " not an integer, + or -.");
		        System.err.println("             continuing to next expression");
		        return null;
		      }

		      if (DEBUG)
		        System.out.println(stack.display());
		    }

		    // assumes last element on stack is answer, as should be the
		    // case if the input file is properly formatted
		    Integer answer = stack.pop();

		    if (answer == null)
		    {
		      System.err.println("RPN, error:  no answer left on stack at end of calculation.");
		      System.err.println("             equation must have been improperly formatted.");
		      System.err.println("             likely no equation was given.  continuing.");
		    }
		    // Expression-ERROR 2
		    if (stack.pop() != null)
		    {
		      System.err.println("RPN, error:  number left on stack after answer.");
		      System.err.println("             equation must have been improperly formatted.");
		      System.err.println("             treating top as answer, and continuing.");
		    }

		    return answer;

		  }

		  /* Returns true if it is a + or - sign.
		   */
		  private boolean isOperator(String token)
		  {
		    if (token.length() != 1)
		      return false;

		    if (token.equals("+") || token.equals("-"))
		      return true;

		    return false;
		  }

		  /* Returns true if it is an integer
		   */
		  private Integer isNumber(String token)
		  {
		    try
		    {
		      Integer x = Integer.parseInt(token);
		      return x;
		    }
		    catch(NumberFormatException e)
		    {
		      return null;
		    }

		  }

		  /*
		   * Performs the given operation, op, (addition or subtraction) on
		   * the top two elements of the stack.
		   *
		   * If the top two respectively are (i.e., op1 is above op2)
		   *
		   * 4        op1
		   * 17       op2
		   *
		   * Then 17-4. (op2-op1), if op is "-".  Similar for addition.
		   *
		   * Assumes op is one of "+" or "-"
		   *
		   * returns false if there is an error.
		   */
		  private boolean calculate(IntegerStackInterface stack, String op)
		  {
		    if (DEBUG)
		      System.out.println("before: " + stack.display());
		    Integer operand1 = stack.pop();
		    Integer operand2 = stack.pop();

		    // Expression-ERROR 3
		    if (operand1 == null || operand2 == null)
		    {
		        System.err.println("RPN, error:  1 or less integers on stack when");
		        System.err.println("             performing operation.");
		        System.err.println("             continuing to next expression");
		        return false;
		    }

		    if (op.equals("+"))
		      stack.push(operand2 + operand1);
		    else
		      stack.push(operand2 - operand1);

		    if (DEBUG)
		      System.out.println("after: " + stack.display());

		    return true;
		  }
		
		  public static void main(String[] args)
		  {
		    if (args.length != 1) // expecting exactly one argument
		    {
		      System.err.println("RPN, error:  did not get exactly 1 arg.");
		      System.err.println("             exiting");
		      System.exit(-1);
		    }
		    IntegerStack calculator = new IntegerStack();
		    calculator.read();
		   
		  }


}	 


And for the Interface:

// a Stack for storing Integers.
// implementing class must have exactly 1 constructor which takes zero
// parameters.
public interface IntegerStackInterface
{
    // push number onto the top of the Stack
    public void push(Integer number);
    // pop and return number from the top of the Stack, returning null
    // if the Stack is empty
    public Integer pop();
    // return a String representing the elements in the Stack.
    //
    // String must have the exact format of these examples:
    //
    //     String               # of elements
    //     ======               =============
    //     "[]"                 empty Stack
    //     "[5]"                1 element
    //     "[5, 4]"             2 elements
    //     "[5, 4, 99]"         3 elements
    //
    // right-most element in String (e.g., 99 for 3-element Stack
    // above) is top of Stack
    public String display();
} 


I'm really unused to using interfaces, and I'm wondering how I'm supposed to implement the three methods within the interface. Any help would be greatly appreciated!

Is This A Good Question/Topic? 0
  • +

Replies To: Creating a Reverse Polish Notation Calculator Using Only Arrays/Stacks

#2 javabie  Icon User is offline

  • D.I.C Head

Reputation: 36
  • View blog
  • Posts: 117
  • Joined: 12-February 10

Re: Creating a Reverse Polish Notation Calculator Using Only Arrays/Stacks

Posted 21 February 2010 - 09:27 PM

you don't implement the method's definition inside the interface. If a class is implementing a interface then that class should give the definition.

Try the following link.
http://java.sun.com/...einterface.html
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1