PROGRAM IS TO CONVERT
AN INFIX NOTATION TO POSTFIX
AN INFIX NOTATION TO POSTFIX
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.util.StringTokenizer;
/**
* This program is a very simple calculator that you can type infix
* expressions of the form "29 + 45 + 3 - 20" into and it will evaluate
* them by adding up or subtracting the numbers, to give you a total.
*
**/
public class SimpleCalc
{
/**
* This is the main entry point for the calculator - it reads an
* expression from the user, evaluates it and prints out the result.
*
**/
public static void main( String argv[] )
{
String expression;
int result;
expression = readExpression();
result = evaluate( expression );
System.out.println( "Total: " + result );
}
/**
* Read a text string containing the expression to be evaluated.
*
* @return the string that the user entered
*
**/
public static String readExpression()
{
BufferedReader keyboard = new BufferedReader( new InputStreamReader( System.in ) );
String expression = "";
System.out.print( "Please enter the expression: " );
try
{
expression = keyboard.readLine();
}
catch ( IOException error )
{
// There is a problem reading from the keyboard
System.err.println( "Error reading from the keyboard: " + error );
System.exit( 1 );
}
return expression;
}
/**
* Evaluate the expression passed in as a parameter and return
* the result.
*
* @param expression the expression to evaluate
* @return the result of the expression
*
**/
public static int evaluate( String expression )
{
StringTokenizer tokenizedExpression = new StringTokenizer( expression );
// we're expecting a number at the start of the expression
boolean expectingOperator = false;
// start with a '+' here because we want to add the very first number
char operator = '+';
int total = 0;
while ( tokenizedExpression.hasMoreTokens() )
{
String symbol = tokenizedExpression.nextToken();
// **** Is it an operator?
if ( symbol.equals( "+" ) || symbol.equals( "-" ) )
{
if ( expectingOperator )
{
// use charAt() to convert it from a string ("+") to a single char ('+')
operator = symbol.charAt( 0 );
// just had an operator, so we're expecting an operand next
expectingOperator = false;
}
else
{
System.err.println( "Error in format of expression: a number expected." );
System.exit( 1 );
}
}
// **** Then it must be an operand
else
{
if ( expectingOperator )
{
System.err.println( "Error in format of expression: an operator is expected." );
System.exit( 1 );
}
else
{
int operand = 0;
try
{
operand = Integer.parseInt( symbol );
}
catch ( NumberFormatException e )
{
System.err.println( "Error in format of expression: number expected." );
System.exit( 1 );
}
switch ( operator )
{
case '+':
total = total + operand;
break;
case '-':
total = total - operand;
break;
}
// just had an operand, so we're expecting an operator next
expectingOperator = true;
}
}
}
return total;
}
}
