/**
* Informatik II - FS2009
* Uebungsserie 4, Aufgabe 1
*
* The class InfToPost allows to convert infix expressions
* to postfix expressions.
* See also lecture script: "Postfixumwandlung mittels Stack" (Folie 138)
*
* @author Philipp Bolliger
**/
public class InfToPost {
Stack stack = new Stack(); // Create a stack with 100 elements
/**
* Outputs the content of the input-array in
* postfix notation
*
* @param input ...ADD YOUR COMMENTS HERE...
**/
public void convert(char[] input) {
int i = 0;
while( i < input.length ) {
//push operands on stack
if(input[i] == '+' || input[i] == '*') {
stack.push( input[i] );
}
// From http://java.sun.com/j2se/1.4.2/docs/api/:
//
// "The Character class wraps a value of the primitive type
// char in an object. An object of type Character contains
// a single field whose type is char. In addition, the
// Character class provides several methods for determining
// a character's category (lowercase letter, digit, etc.)
// and for converting characters from uppercase to lowercase
// and vice versa."
//
// isDigit( char c ) is a method of the Character class, which
// for a character c ascertains whether c is a digit or not.
// The same functionality may be obtained through the
// expression: "(c >= '0' && c <= '9')"
//print digit
if( Character.isDigit( input[i] ) ) {
System.out.print( " " + input[i] );
}
//print operand
if( input[i] == ')' ) {
System.out.print( " " + (char)stack.pop() );
}
i++;
} // end while()
System.out.println();
// Think about...
// The following check may detect a syntax error!
if( ! stack.empty() ) {
System.out.println( "Error: uncorrect expression" );
}
}
/**
* Test inputs:
* ((5+13)*((23+17)*81))
* (12+(5*((76+42)+19)))
**/
public static void main(String[] args) {
if( args.length == 0 || args.length > 1 ) {
System.out.print("Invalid Input!");
System.out.println(" Please enter an infix expression" +
" as one-string argument.");
System.out.println("Example: java InfToPost \"((7+5)*9)\"" );
System.exit( 1 );
}
//convert input string in a char array
char[] input = args[0].toCharArray();
InfToPost expression = new InfToPost();
//Convert and print coverted expression
expression.convert(input);
}
}