Here listed above is my question above and example of how it would be done is be
ID: 3851061 • Letter: H
Question
Here listed above is my question above and example of how it would be done is below. I need this coded in Java as an example. This is a warm up for me to understand the project I will be diving in. The code should be fairly simple but I just do not understand it.
Edit* ignore the polish notation comment I want the output to be like I had noted below.
All in all I need code in java where you can input any expression as a string like (((1+2)÷3)×4) and it follows the logic of the tree below to solve it and it spits out the solution without the parenthesis except on the 1st calculation of the expression. So the 2 outputs it would spit back out afe. (1+2)÷3×4 and the result as 4
Thank You
Explanation / Answer
public static double cal(final String str) {
return new Object() {
int pos = -1, ch;
void nextChar() {
ch = (++pos < str.length()) ? str.charAt(pos) : -1;
}
boolean eq(int charToEat) {
while (ch == ' ') nextChar();
if (ch == charToEat) {
nextChar();
return true;
}
return false;
}
double parse() {
nextChar();
double x = parseExpression();
if (pos < str.length()) throw new RuntimeException("Unexpected: " + (char)ch);
return x;
}
double parseExpression() {
double x = parseTerm();
for (;;) {
if (eq('+')) x += parseTerm();
else if (eq('-')) x -= parseTerm();
else return x;
}
}
double parseTerm() {
double x = parseFactor();
for (;;) {
if (eq('*')) x *= parseFactor();
else if (eq('/')) x /= parseFactor();
else return x;
}
}
double parseFactor() {
if (eq('+')) return parseFactor();
if (eq('-')) return -parseFactor();
double x;
int startPos = this.pos;
if (eq('(')) {
x = parseExpression();
eat(')');
} else if ((ch >= '0' && ch <= '9') || ch == '.') {
while ((ch >= '0' && ch <= '9') || ch == '.') nextChar();
x = Double.parseDouble(str.substring(startPos, this.pos));
} else if (ch >= 'a' && ch <= 'z') {
while (ch >= 'a' && ch <= 'z') nextChar();
String func = str.substring(startPos, this.pos);
x = parseFactor();
} else {
throw new RuntimeException("Unexpected: " + (char)ch);
}
return x;
}
}.parse();
}