L. Lasiter L. Lasiter - 2 months ago 6
Java Question

Operators only being read as "power to" or "^" need operators "+, -, *, /, ^" to all be useable

public class ExpressionEvaluator {
private String infix;
private String postfix;
private Stack<String> s;
private Queue<String> q;

public ExpressionEvaluator(){
s = new Stack<String>();
q = new Queue<String>();
}

public String processInput(String s){
infix = s;
convertToPostfix(s);

return evaluatedPostfix();
}

private boolean isOp(String token) {
return token.equals("+") || token.equals("-") || token.equals("*") || token.equals("/") ||
token.equals("^");
}

private boolean lowerPrecedence(String op1, String op2){
switch (op1) {
case "+":
case "-":
return !(op2.equals("+") || op2.equals("-"));
case "*":
case "/":
return op2.equals("^") || op2.equals("(");
case "^":
return op2.equals("(");
default:
return false;
}
}

public void convertToPostfix(String infix) {
StringTokenizer st = new StringTokenizer(infix);
while (st.hasMoreTokens()) {
String token = st.nextToken();
if (token.equals("("))
s.push(token);
if (token.equals(")")){
while (!token.equals("(")){
q.enqueue(s.pop());
}
}
if (isOp(token)){
while (!s.isEmpty() && !s.peek().equals("(") &&
lowerPrecedence((String)s.peek(),token)){
q.enqueue(s.pop());
}
s.push(token);
} // end if token is an operator
else
q.enqueue(token);

} // end while loop checking each token
while (!s.isEmpty()){
q.enqueue(s.pop());
} // postfix equation is in queue


}

public String evaluatedPostfix() {
String result;
String answer;
double num;
double num2;
double retVal = 0;
while (!q.isEmpty()){
if (!isOp(q.peek()))
s.push(q.dequeue());
else if (isOp(q.peek())) {
num = Double.parseDouble(s.pop());
num2 = Double.parseDouble(s.pop());
switch (q.dequeue()) {
case "+": retVal = num + num2;
case "-": retVal = num2 - num;
case "*": retVal = num * num2;
case "/": retVal = num2 / num;
case "^": retVal = Math.pow(num2, num);
}
result = Double.toString(retVal);
s.push(result);
}
else
return "Error";
}
answer = s.pop();
return answer;
}

public static void main(String[] args) {

ExpressionEvaluator var = new ExpressionEvaluator();
String k;

k = "2 + 3";
System.out.println(var.processInput(k));

}

}


So I'm testing this class and no matter what operator use in the string k it gets read as a "^", for example this string "2 + 3" will come to 8 in the console. So 2^3, Is there anything I can do to change this?

EJP EJP
Answer

Each of those case statements in evaluatedPostfix() needs abreak.