Yar

Sign in to follow this  
  • entries
    208
  • comments
    383
  • views
    65546

jRPN, because I can't sleep...

Sign in to follow this  
H_o_p_s

143 views



Well... couldn't go to sleep so I wrote a ReversePolishNotation calculator in Java. For those of you that don't know what RPN is here is a crash course:
input >2 + 2
output>ERROR: NOT ENOUGH ARGUMENTS

input >2 2 +
output>4

input >2 2 + 2 + 3 /
output>2

Now for those of you that still don't get it, you have to think about it in stacks. Every space seperates a new entry into the stack. SO, by entering "2 2 2" you make a stack that looks like this:
0:2
1:2
2:2

When you try to put a math operator into the stack, it takes the two numbers before and does the operation erases them, and inserts the output of the operation. So "3 2 2 + 4 / -" does this:
0:3
1:2
2:2
-----operation
0:3
1:4
2:4
-----operation
0:3
1:1
-----operation
0:2

And if you still aren't getting it, here is the source code:

import java.io.*;
import java.util.ArrayList;
import java.util.StringTokenizer;

public class jRPN {

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String ci;
int i = 0;
ArrayList b1;

public jRPN() {
b1 = new ArrayList();
while (true) {
ci = getInput();
test();
}
}

public String getInput() {
try {
return br.readLine();
} catch ( IOException e) {}
return "";
}

public void test() {
StringTokenizer st = new StringTokenizer(ci);
while (st.hasMoreTokens()) {
b1.add(i, st.nextToken());
if (b1.get(i).equals("+") & (i >= 2) )
b1.add(i+1, new String(""+ (Float.parseFloat((String)b1.get(i-2)) + Float.parseFloat((String)b1.get(i-1))) ) );
if (b1.get(i).equals("-"))
b1.add(i+1, new String(""+ (Float.parseFloat((String)b1.get(i-2)) - Float.parseFloat((String)b1.get(i-1))) ) );
if (b1.get(i).equals("/"))
b1.add(i+1, new String(""+ (Float.parseFloat((String)b1.get(i-2)) / Float.parseFloat((String)b1.get(i-1))) ) );
if (b1.get(i).equals("*"))
b1.add(i+1, new String(""+ (Float.parseFloat((String)b1.get(i-2)) * Float.parseFloat((String)b1.get(i-1))) ) );
if (b1.get(i).equals("+") || b1.get(i).equals("-") || b1.get(i).equals("/") || b1.get(i).equals("*") ) {
if ( i >= 2) {
b1.remove(i);
i--;
b1.remove(i);
i--;
b1.remove(i);
System.out.println("jRPN> " + b1.get(i));
} else {
System.out.println("jRPN> Not enough arguments.");
b1.remove(i);
i--;
}
}
i++;
}
}

public static void main(String[] args) {
jRPN app = new jRPN();
}
}





Also added to my showcase...
Sign in to follow this  


2 Comments


Recommended Comments

On my HP48GX (with a huge 128k of ram...) the manual referred to it as Reverse Polish Notation... however I have heard it called postfix expression as well...

Share this comment


Link to comment

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now