• entries
208
383
• views
66183

# jRPN, because I can't sleep...

165 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("&#47;"))				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("&#47;") || 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();	}}

I have always heard of that as called a "postfix expression."

Anyway, I thought you might find this interesting/useful/whatever.

postfix to infix

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...

## Create an account

Register a new account

×

## Important Information

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!