Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

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



strin with parenthes exatly see, of operntien The loye should follow a ree here each ope for Ly node and the last operat becomes the nestiny nele (2 The output wouw be apoloh nstat induding parenthe of the Hirst sub operation output (I 2) 3 x 4 other exam Iti tr all addutin ope it would be ktt (It) t2 :s what t become I need to do thi) in Suva where the lon an follons tree as shown above a and

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();
}