Parsing/RPN calculator algorithm: Difference between revisions

Line 2,148:
{{works with|Java|1.5+}}
Supports multi-digit numbers and negative numbers.
<lang java5>import java.util.LinkedList;
import java.util.LinkedList;
 
public class RPN{
public static void evalRPNmain(String[] exprargs) {
evalRPN("3 4 2 * 1 5 - 2 3 ^ ^ / +");
String cleanExpr = cleanExpr(expr);
}
 
private static Stringvoid cleanExprevalRPN(String expr){
LinkedList<Double> stack = new LinkedList<Double>();
System.out.println("Input\tOperation\tStack after");
for (String token :cleanExpr expr.split("\\s")){
System.out.print(token + "\t");
}else if (token.equals("*")) {
Double tokenNum = null;
try{
tokenNum = Double.parseDouble(token);
}catch(NumberFormatException e){}
if(tokenNum != null){
System.out.print("Push\t\t");
stack.push(Double.parseDouble(token+""));
}else if(token.equals("*")){
System.out.print("Operate\t\t");
double secondOperand = stack.pop();
double firstOperand = stack.pop();
stack.push(firstOperand * secondOperand);
} else if (token.equals("/")) {
System.out.print("Operate\t\t");
double secondOperand = stack.pop();
double firstOperand = stack.pop();
stack.push(firstOperand / secondOperand);
} else if (token.equals("-")) {
System.out.print("Operate\t\t");
double secondOperand = stack.pop();
double firstOperand = stack.pop();
stack.push(firstOperand - secondOperand);
} else if (token.equals("+")) {
System.out.print("Operate\t\t");
double secondOperand = stack.pop();
double firstOperand = stack.pop();
stack.push(firstOperand + secondOperand);
} else if (token.equals("^")) {
System.out.print("Operate\t\t");
double secondOperand = stack.pop();
double firstOperand = stack.pop();
stack.push(Math.pow(firstOperand, secondOperand));
} else{//just in case{
System.out.printlnprint("ErrorPush\t\t");
return;try {
tokenNum = stack.push(Double.parseDouble(token+""));
} catch (NumberFormatException e) {}
System.out.println("\nError: invalid token " + token);
return;
try{ }
}
System.out.println(stack);
}
if (stack.size() > 1) {
System.out.println("Error, too many operands: " + stack);
return;
}
System.out.println("Final answer: " + stack.pop());
}
}
}</lang>
private static String cleanExpr(String expr){
//remove all non-operators, non-whitespace, and non digit chars
return expr.replaceAll("[^\\^\\*\\+\\-\\d/\\s]", "");
}
public static void main(String[] args){
evalRPN("3 4 2 * 1 5 - 2 3 ^ ^ / +");
}
}</lang>
{{out}}
<pre>Input Operation Stack after