Java Reference
In-Depth Information
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
public static char getToken() throws IOException {
int n;
while ((n = System.in.read()) == ' ') ; //read over blanks
if (n == '\r') return '\0';
return (char) n;
} //end getToken
public static int precedence(char c) {
//Returns the precedence of the given operator
if (c == '(') return 0;
if (c == '+' || c == '-') return 3;
if (c == '*' || c == '/') return 5;
return -99; //error
} //end precedence
} //end class InfixToPostfix
class NodeData {
char ch;
public NodeData(char c) {
ch = c;
}
public char getData() {return ch;}
public static NodeData getRogueValue() {return new NodeData('$');}
} //end class NodeData
The job of reading the expression and converting to postfix is delegated to the function readConvert . This
outputs the postfix form to a character array, post . So as not to clutter the code with error checking, we assume that
post is big enough to hold the converted expression. The function returns the number of elements in the postfix
expression.
The function printPostfix simply prints the postfix expression.
The following is a sample run of Program P4.5:
Type an infix expression and press Enter
(7 - 8 / 2 / 2) * ((7 - 2) * 3 - 6)
The postfix form is
7 8 2 / 2 / - 7 2 - 3 * 6 - *
 
Search WWH ::




Custom Search