Anonymous user
Parsing/RPN calculator algorithm: Difference between revisions
→{{header|Java}}
Line 2,148:
{{works with|Java|1.5+}}
Supports multi-digit numbers and negative numbers.
<lang java5>
import java.util.LinkedList;
public class RPN{
public static void
evalRPN("3 4 2 * 1 5 - 2 3 ^ ^ / +");▼
}▼
LinkedList<Double> stack = new LinkedList<Double>();
System.out.println("Input\tOperation\tStack after");
for (String token :
System.out.print(token + "\t");
try{▼
tokenNum = Double.parseDouble(token);▼
}catch(NumberFormatException e){}▼
▲ }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
System.out.
System.out.println("\nError: invalid token " + token);
return;
}
System.out.println(stack);
}
if (stack.size() > 1) {
System.out.println("Error, too many operands: " + stack);
return;
}
System.out.println("Final answer: " + stack.pop());
}
▲ private static String cleanExpr(String expr){
▲ }
▲ evalRPN("3 4 2 * 1 5 - 2 3 ^ ^ / +");
▲ }
▲}</lang>
{{out}}
<pre>Input Operation Stack after
|