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

Write a java program to parse and evaluate programs consisting of assignment and

ID: 3548088 • Letter: W

Question

Write a java program to parse and evaluate programs consisting of assignment and print statements with fully parenthesized arithmetic expressions (see Program 4.3.5). For example, given the input
A = 5
B = 10
C = A + B
D = C * C
print(D)
your program should print the value 225. Assume that all variables and values are of type double. Use a symbol table to keep track of variable names.
Experiments
Write test programs to demonstrate that your Interpreter works correctly.
In particular, write a program to evaluate polynomials of the form:
ax^5 + bx^4 + cx^3 + dx^2 + ex + f
Discuss the limitations of this language. What kinds of programs can you write in Java that you cannot write here?

Explanation / Answer

We can solve this kind of problems using stacks. The following program works fine for the given problem. public class Evaluate { public static void main(String[] args) { Stack ops = new Stack(); Stack vals = new Stack(); while (!StdIn.isEmpty()) { String s = StdIn.readString(); if (s.equals("(")) ; else if (s.equals("+")) ops.push(s); else if (s.equals("-")) ops.push(s); else if (s.equals("*")) ops.push(s); else if (s.equals("/")) ops.push(s); else if (s.equals("sqrt")) ops.push(s); else if (s.equals(")")) { String op = ops.pop(); double v = vals.pop(); if (op.equals("+")) v = vals.pop() + v; else if (op.equals("-")) v = vals.pop() - v; else if (op.equals("*")) v = vals.pop() * v; else if (op.equals("/")) v = vals.pop() / v; else if (op.equals("sqrt")) v = Math.sqrt(v); vals.push(v); } else vals.push(Double.parseDouble(s)); } StdOut.println(vals.pop()); } }
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote