D day - 1 year ago 96
Java Question

# How to use math.pow() to do calculations in Expression class?

in my program I have written an evalPostfix() method that also uses my applyOperator() method.

However, one of the goals that I need to achieve is to perform exponentiation, using math.pow() to do the calculation. I also need to cast the end result back into an int.

I am unsure on how to get started, and how to implement Math.pow() into my evalPostfix() method in my Expression class.

Here is my code:

``````public class Expression {
private static final String SPACE = " ";
private static final String PLUS = "+";
private static final String MINUS = "-";

public static int rank(String operator) {
switch (operator) {
case "^":       //5
return 3;
case "*":
case "/":
return 2;
case PLUS:
case MINUS:     //2
return 1;
case "()":      //6
return 0;
default:
return -1;
}
}

public static boolean isOperator(String token) {     //4
if (rank(token) > 0){
return true;
}
return false;
}

public static int applyOperator(String operator,int op1,int op2){     //7
switch (operator) {
case PLUS:
return op1+op2;
case MINUS:
return op1-op2;
case "*":
return op1*op2;
case "/":
return op1/op2;
default:
return -1;
}
}

public static String toPostfix(String infixExpr) {
StringBuilder output = new StringBuilder();
Stack<String> operators = new ArrayStack<>();
for (String token: infixExpr.split("\\s+")) {
if (isOperator(token)) { // operator //4
// pop equal or higher precedence
while (!operators.isEmpty() &&
rank(operators.peek()) >= rank(token)) {
output.append(operators.pop() + SPACE);
}
operators.push(token);
} else {               // operand
output.append(token + SPACE);
}
}
while (!operators.isEmpty()) {
output.append(operators.pop() + SPACE);
}
return output.toString();
}

public static int evalPostfix(String infixExpr) {     //8
Stack <String> s = new ArrayStack<String>();
String operand = null;
for(int i = 0; i < infixExpr.length(); i++) {
if (Character.isDigit(infixExpr.charAt(i)))
s.push(infixExpr.charAt(i) + "");
else {
if (s.size() > 1) {
int value1 = Integer.parseInt(s.pop());
int value2 = Integer.parseInt(s.pop());
s.push(applyOperator(infixExpr.charAt(i) + "", value1, value2) + "");
}
}
}
return Integer.parseInt(s.pop());
}

public static void main(String[] args) {
System.out.println(rank("/"));
String infix = ")a * b( * c + d ^ e / f";
System.out.println(toPostfix(infix));
System.out.print("Using applyOperator method, 7 * 3 = ");
System.out.println(applyOperator("*", 3, 7));
System.out.print("Using applyOperator method, 50 + 12 = ");
System.out.println(applyOperator("+", 50, 12));
}
}
``````