I already have an infix to postfix converter, now I want to get the answer from the postfix notation.
Here is my code to evaluate a given postfix notation and (hopefully) get the answer:
public class testEVAL {
private StackArray SA;
private String input;
private int postfixEVAL;
//start constructor
public testEVAL(String input){
SA = new StackArray();
this.input = input;
//postfixEVAL =;
}//end constructor
private int obj2intCONVERT(Object obj){
return Integer.parseInt(obj.toString());
}// converting popped Objects into Integers
//start operation methods
private int add(int a,int b){
return a+b;
}
private int sub(int a,int b){
return a-b;
}
private int mul(int a,int b){
return a*b;
}
private int div(int a,int b){
return a/b;
}//end operation methods
public int postEVALUATED(){
postEVAL();
return postfixEVAL;
}//returns the answer of the given postfix notation
private boolean isDIGIT(char ch){
return Character.isDigit(ch);
}//is digit sort of override
private int operatorCHK(char ch){
int ret=-1;
switch(ch){
case '+':
ret=1;
break;
case '-':
ret=2;
break;
case '*':
ret=3;
break;
case '/':
ret=4;
break;
}
return ret;
}//returns 1 for addition, 2 for subtraction, 3 for multiplication and 4 for division
private void postEVAL(){
int numA,numB,numANS=0;
for(int i = 0; i < input.length();++i){
if(input.charAt(i) != '+' && input.charAt(i) != '-' && input.charAt(i) != '*' && input.charAt(i) != '/'){
SA.push(input.charAt(i));
}
else if(!SA.isEmpty()){
numB = SA.intPOP();
numA = SA.intPOP();
switch(operatorCHK(input.charAt(i))){
case '1':
numANS=add(numA,numB);
SA.push(numANS);
break;
case '2':
numANS=sub(numA,numB);
SA.push(numANS);
break;
case '3':
numANS=mul(numA,numB);
SA.push(numANS);
break;
case '4':
numANS=div(numA,numB);
SA.push(numANS);
break;
}//end switch
}//end ifs
if(i==input.length()-1){
postfixEVAL = numANS;
}
}//end for
}
}
My problem is, the output returns 0 (numANS "should" have the answer by the last iteration in the for loop in the postEVAL method)...
Any help would be much appreciated!