How to make a RPN calculator (Java)

Khalob C picture Khalob C · May 9, 2013 · Viewed 10.4k times · Source

I have an assignment and I need a bit of help, there seems to be an error when doing more than one calculation using RPN format. I use the example input as given in the link below. On the first input (16 3 7 + *) it gives me the correct answer (160). But, the next two inputs (4 32.125 13 – * 20 +) and (5 –3 * 4 2 / 6 3 1 – / + +) return "error." Thanks for your help in advance, if you need some more information don't be afraid to ask. The assignment details: Details

My code so far:

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

public class RPNcalculator {
public static void main(String[] args) {

    String fileName="RPNInput.txt";
    String fileName2="RPNOutput.txt";
    Scanner inputStream = null;
    PrintWriter outputStream = null;

    //read
    try{
        inputStream = new Scanner(new File(fileName)); //try to open the file
    }
    catch(Exception e){
        System.out.println("Could not open the file named "+ fileName); // if it doesn't find it, tell them
        System.exit(0);  // and then exit.
    }

    //write
    try{
        outputStream = new PrintWriter(new FileOutputStream(fileName2,true)); //try to create the file
    }
    catch(Exception e){
        System.out.println("Could not open the file named "+ fileName2); // if it doesn't find it, tell them
        System.exit(0);  // and then exit.
    }

    while(inputStream.hasNextLine()){
        String equation = inputStream.nextLine();
        if (equation==null)  break;
        Stack<String> tks = new Stack<String>();
        tks.addAll(Arrays.asList(equation.trim().split("[ \t]+"))); //remove spaces and split into list.
          if (tks.peek().equals(""))  continue; //if tks equals nothing
          try  {
            double r = evaluaterpn(tks); //set the variable r to the equation answer.
            if (!tks.empty())  throw new Exception(); //if the list is not empty, print out answer.
            System.out.println(r);
          }
          catch (Exception e)  {System.out.println("error");}
          }
        }


  private static double evaluaterpn(Stack<String> tks) throws Exception  {
        String tk = tks.pop();
        double x,y;
        try  {x = Double.parseDouble(tk);}
        catch (Exception e)  {
          y = evaluaterpn(tks);  x = evaluaterpn(tks);
          if      (tk.equals("+"))  x += y;
          else if (tk.equals("-"))  x -= y;
          else if (tk.equals("*"))  x *= y;
          else if (tk.equals("/"))  x /= y;
          else throw new Exception();
        }
        return x;
      }
}

Answer

Igor Deruga picture Igor Deruga · May 9, 2013

Very simple :) you're using the bad "-" sign. When you put a breakpoint at the line "else throw new Exception();", you see that tk is equal to "--" (long "minus" sign). Either copy it into your code instead of normal minus sign or edit your file in a simple text editor.