Reputation: 409
I'm trying to implement this pseudo-code in java, to evaluate an arithmetic expression. But I keep getting the last digit: ie if i do 1+2, i'd just get 2; I don't know what I'm doing incorrectly, so If anyone has any idea, please let me know!!
import java.util.Stack;
public class Main {
static Stack<String> ops = new Stack<String>();
static Stack<Double> vals = new Stack<Double>();
private static void doOP() {
double x = vals.pop();
double y = vals.pop();
String op = ops.pop();
double v = 0;
if (op.equals("+")) {
v = y + x;
} else {
if (op.equals("-")) {
v = y - x;
} else {
if (op.equals("*")) {
v = y * x;
} else {
if (op.equals("/")) {
v = y / x;
}
}
}
}
vals.push(v);
}
private static void repeatOps(String refOp) {
while ((vals.size() > 1) && (prec(refOp) <= prec(ops.peek()))) {
doOP();
}
}
private static int prec(String refOp) {
String[] bodmas = new String[] { "(", ")", "/", "*", "+", "-", "$" };
int i = 0;
for (String operation : bodmas) {
if (refOp.equals(operation)) {
return i;
}
i++;
}
return -0;
}
private static boolean isNumber(String number) {
try {
@SuppressWarnings("unused")
double d = Double.parseDouble(number);
} catch (Exception e) {
return false;
}
return true;
}
private static Double evalExp(String exp) {
for (char z : exp.toCharArray()) {
if (isNumber(z + "")) {
vals.push(Double.parseDouble(z + ""));
} else {
repeatOps(z + "");
ops.push(z + "");
}
}
repeatOps("$");
return vals.peek();
}
public static void main(String[] args) {
System.out.println(evalExp("3*2"));
}
}
Upvotes: 0
Views: 1195
Reputation: 159096
Your prec()
method is inverted and incorrect.
$
should be lowest precedence, meaning lowest value, e.g. 0
.
+
and -
should have same precedence.
*
and /
should have same precedence.
(
and )
are not binary operators, and cannot be handled with the described logic.
So, fix prec
to return 0
for $
, 1
for +
and -
, and 2
for *
and /
.
Upvotes: 1