- Exercise to implement RPN evaluator.
Exercise 2.
- Translator from arithmetic expressions to RPN.
Here is the list of rules we developed in class to
translate arithmetic expressions to RPN, using a stack
for the translation. (Note that the RPN evaluator
uses a stack of doubles for intermediate
values. The translator described here
uses a stack of chars
to hold pending operators.)
Rules to translate an arithmetic expression to RPN:
Rules for each input char
(go on to next input char unless otherwise stated)
Fetch next char, call it ch
- if ch is an operand, move it to output.
From now on ch is an operator or '(' or ')'.
- if stack is empty, add ch to stack.
- if ch is '(', add ch to stack.
From now on, stack is not empty. Use top for its top char
(just peeked at, not popped).
- if ch is ')', remove chars from stack and output down
to '(' on stack, which is thrown away.
- if top is '(', add ch to stack.
From now on, both ch and
top are regular operators.
- if prec(ch) > prec(top),
add ch to stack.
- if prec(ch) < prec(top),
move top to output, and
DO NOT MOVE ON TO NEXT INPUT CHAR.
- if prec(ch) == prec(top) and
left-to-right associativity,
move top to output,
and DO NOT MOVE ON TO NEXT INPUT CHAR.
- if prec(ch) == prec(top)
and right-to-left associativity,
add top to stack.
- at end, move everything on stack to output.
- Exercise to implement translator.
Exercise 3.
- Evaluator of arithmetic expressions.
This is just a matter of feeding a string containing an
arithmetic expression into the translator to produce a
string containing RPN. Then this string is fed
into the RPN evaluator to get a final value. The Java
code could look something like:
GetNext getNext = new GetNext(); // input class
Trans trans = new Trans(); // new translater
Eval eval = new Eval(); // new evaluator
String s = getNext.getNextString(); // fetch string
System.out.println("Input: " + s);
String resStr = trans.translate(s); // produce RPN
System.out.println("RPN string: " + resStr); // print RPN
double res = eval.evaluateRPN(resStr);
System.out.println("Value: " + res); // print value
- Here is some material about file I/O and copying,
showing programs in C, C++, and Java.
file copy.
Here is material about the standard input, output and error files:
error output.