Java Reference
In-Depth Information
Using this definition of
NodeData
, Program P4.5 will work fine if we simply replace all occurrences of
getData
with
getCharData
.
The function
eval
, which evaluates an expression given its postfix form, is shown as part of Program P4.6. We test
eval
by placing the following as the last statement in
main
:
System.out.printf("\nIts value is %d\n", eval(post, n));
The classes
Node
and
Stack
are not shown in Program P4.6. The class
Node
is the same as that in Program P4.3.
The class
Stack
is the same as that in Program P4.3 with the addition of
peek()
.
Program P4.6
import java.io.*;
public class EvalExpression {
public static void main(String[] args) throws IOException {
char[] post = new char[255];
int n = readConvert(post);
printPostfix(post, n);
System.out.printf("\nIts value is %d\n", eval(post, n));
} //end main
public static int readConvert(char[] post) throws IOException {
//Read the expression and convert to postfix. Return the size of postfix.
Stack S = new Stack();
int h = 0;
char c;
System.out.printf("Type an infix expression and press Enter\n");
char token = getToken();
while (token != '\0') {
if (Character.isDigit(token)) post[h++] = token;
else if (token == '(') S.push(new NodeData('('));
else if (token == ')')
while ((c = S.pop().getCharData()) != '(') post[h++] = c;
else {
while (!S.empty() &&
precedence(S.peek().getCharData()) >= precedence(token))
post[h++] = S.pop().getCharData();
S.push(new NodeData(token));
}
token = getToken();
}
while (!S.empty()) post[h++] = S.pop().getCharData();
return h;
} //end readConvert
public static void printPostfix(char[] post, int n) {
System.out.printf("\nThe postfix form is \n");
for (int h = 0; h < n; h++) System.out.printf("%c ", post[h]);
System.out.printf("\n");
} //end printPostfix
Search WWH ::
Custom Search