import java.util.NoSuchElementException;
import java.util.StringTokenizer;

/**
 * A 5-function calculator that can evaluate expressions
 * consisting of an integer operand followed by an operator 
 * followed by an integer operand (e.g.,5+3)
 *
 * @author  Prof. David Bernstein, James Madison University
 * @version 1.0
 */
public class IntegerCalculator
{
    private String         operators;

    /**
     * Default Constructor
     */
    public IntegerCalculator()
    {
	operators = new String("%/x-+");
    }


    /**
     * Evaluate an expression
     *
     * @param  expression   The String containing the expression
     * @return              The result of evaluating the expression
     * @throws ArithmeticException     If an arithmetic problem arises
     * @throws NoSuchElementException  If an operand or operator is missing
     * @throws NumberFormatException   If an operand is not an int
     */
    public int calculate(String expression) throws ArithmeticException, 
						   NoSuchElementException, 
						   NumberFormatException
    {
	int                    left, result, right;
	String                 leftS, operator, rightS;
	StringTokenizer        st;


	// Construct a StringTokenizer that uses the operators
	// as delimiters and returns the delimiters as
	// tokens
	st = new StringTokenizer(expression, operators, true);


	// Parse the expression
	leftS    = st.nextToken();
	operator = st.nextToken();
	rightS   = st.nextToken();

        // Create the left side operand
        left = 0;

        // Initialize the left side operand
	left  = Integer.parseInt(leftS);

        // Create the right side operand
        right = 0;

        // Initialize the right side operand
	right = Integer.parseInt(rightS);


	// Perform the operation
	if      (operator.equals("%")) result = left % right;
	else if (operator.equals("/")) result = left / right;
	else if (operator.equals("x")) result = left * right;
	else if (operator.equals("-")) result = left - right;
	else                           result = left + right; // "+" 

        // Return the result
	return result;
    }

}
