Hi I just started to use java from using other programming languages and decided to convert one of my old projects' it a Reverse Polish notation class to do calculations very basic but works hope you find it useful comments welcome.
jrpn class
Code:
import java.util.Stack;
public class jrpn {
private double m_result;
private double max(double value1, double value2){
if(value1 > value2){
return value1;
}
else{
return value2;
}
}
private double min(double value1, double value2){
if(value1 < value2){
return value1;
}
else{
return value2;
}
}
private Boolean isNum(String value){
try {
double N;
N = Double.parseDouble(value);
return true;
}catch (NumberFormatException E){
return false;
}
}
private boolean isOperator(String value){
return value.equals("+") || value.equals("-")
|| value.equals("*") || value.equals("/")
|| value.equals("%");
}
public jrpn(String expression){
this.m_result = 0.0;
Stack<Double>stack = new Stack<>();
String[]tokens = expression.split(" ");
String S0;
Double A;
Double B;
label:
for (String S : tokens) {
S0 = S.trim().toUpperCase();
if (S0.length() > 0) {
if (isNum(S0)) {
//Push numbers onto stack.
stack.push(Double.parseDouble(S));
} else {
if (isOperator(S0)) {
A = stack.pop();
B = stack.pop();
switch (S0) {
case "+":
stack.push(B + A);
break;
case "*":
stack.push(B * A);
break;
case "-":
stack.push(B - A);
break;
case "/":
if (A == 0) {
System.out.println("Division by zero.");
stack.push(0.0);
break label;
} else {
stack.push(B / A);
}
break;
case "%":
stack.push(B % A);
break;
default:
stack.push(0.0);
break;
}
}
else{
A = stack.pop();
switch (S0){
case "SIN":
stack.push(Math.sin(A));
break;
case "COS":
stack.push(Math.cos(A));
break;
case "LOG":
stack.push(Math.log(A));
case "SQR":
stack.push((A * A));
break;
case "EXP":
stack.push(Math.exp(A));
break;
case "MIN":
B = stack.pop();
stack.push(min(A,B));
break;
case "MAX":
B = stack.pop();
stack.push(max(A,B));
break;
}
}
}
}
}
this.m_result = stack.pop();
}
public double getResult(){
return this.m_result;
}
}
Main example using the class.
Code:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
String exp;
System.out.print("Enter Expression : ");
Scanner scan = new Scanner(System.in);
exp = scan.nextLine();
jrpn rpn = new jrpn(exp);
System.out.print(rpn.getResult());
scan.close();
}
}