How to make a RPN calculator (Java) -


i have assignment , need bit of help, there seems error when doing more 1 calculation using rpn format. use example input given in link below. on first input (16 3 7 + *) gives me correct answer (160). but, next 2 inputs (4 32.125 13 – * 20 +) , (5 –3 * 4 2 / 6 3 1 – / + +) return "error." in advance, if need more information don't afraid ask. assignment details: details

my code 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 open file     }     catch(exception e){         system.out.println("could not open file named "+ filename); // if doesn't find it, tell them         system.exit(0);  // , exit.     }      //write     try{         outputstream = new printwriter(new fileoutputstream(filename2,true)); //try create file     }     catch(exception e){         system.out.println("could not open file named "+ filename2); // if doesn't find it, tell them         system.exit(0);  // , 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 , split list.           if (tks.peek().equals(""))  continue; //if tks equals nothing           try  {             double r = evaluaterpn(tks); //set variable r equation answer.             if (!tks.empty())  throw new exception(); //if list 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;       } } 

very simple :) you're using bad "-" sign. when put breakpoint @ line "else throw new exception();", see tk equal "--" (long "minus" sign). either copy code instead of normal minus sign or edit file in simple text editor.


Comments

Popular posts from this blog

linux - xterm copying to CLIPBOARD using copy-selection causes automatic updating of CLIPBOARD upon mouse selection -

qt - Errors in generated MOC files for QT5 from cmake -