This solution focuses on the design of classes, not the actual push and pop stack part. I will include that part of the code as well. The current code has 2 operators (plus and minus).
If we add another subclass under Token, is there a way that we don't need to check in
processInput()
what each operator is and perform the right calculation?
I didn't know how to answer that question. I looked into Java Reflection, but still don't know how reflection can help me in this case. Can anyone shed some light on how I can make this design better?
I want to allow people to add new operators, multiply and divide, and maybe make their own definition for special operators.
This application will take input string like "1 2 + 1 -" and output 2 because "1 2 + 1 -" is the reverse Polish notation for (1+2)-1 = 2.
import java.util.*;
public class RPNCalculator {
public static Stack<Integer> stack;
//assume this string has integers and legal operators +,- and deliminated by space
// an example would be "12 2 + 1 -"
private static String input;
static String operators ="+-";
public RPNCalculator(String userInput){
input = userInput;
stack = new Stack<Integer>();
}
public void processInput(){
StringTokenizer st = new StringTokenizer(input, " ");
while (st.hasMoreTokens()){
String str = st.nextToken();
if(!operators.contains(str)){
stack.push(Integer.parseInt(str));
}
else{
if(str.equals("+")){
Plus obj = new Plus();
obj.calc();
}
else if(str.equals("-")){
Minus obj2 = new Minus();
obj2.calc();
}
}
}
System.out.println(stack.pop());
}
}
public abstract class Token {
abstract void calc();
}
public class Minus extends Token {
@Override
void calc() {
int a = RPNCalculator.stack.pop();
int b = RPNCalculator.stack.pop();
RPNCalculator.stack.push(b-a);
}
}
public class Plus extends Token {
@Override
void calc() {
int a = RPNCalculator.stack.pop();
int b = RPNCalculator.stack.pop();
RPNCalculator.stack.push(a+b);
}
}
public class RPNDriver {
public static void main(String[] args) {
System.out.println("starting calculator...");
RPNCalculator rpn = new RPNCalculator("1 2 +");
rpn.processInput();
}
}