import java.util.NoSuchElementException;
import java.util.StringTokenizer;

/**
 * A 5-function calculator that can evaluate expressions
 * consisting of an operand followed by an operator followed by an operand
 * (e.g.,5+3)
 * 
 * @author  Professor Elizabeth Adams,James Madison University
 * @version 1.0
 */
 public class CalculatorA
 {
    private String         operators;

    /**
     * Default Constructor
     */
    public CalculatorA()
    {
	 	operators = new String("%/x-+"); // note only allowing lower case x for multiplication here
    }


    /**
     * 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                    leftOperand, result, rightOperand;
					String                 leftString, operator, rightString;
					StringTokenizer        myStringTokenizer;


							// Construct a StringTokenizer that uses the operators
							// as delimiters and returns the delimited tokens
					myStringTokenizer = new StringTokenizer(expression, operators, true);

							// Try and get the three tokens - are there 3? 
							//(if not, throw a NoSuchElementException)
					leftString  	= myStringTokenizer.nextToken();
					operator 		= myStringTokenizer.nextToken();
					rightString   	= myStringTokenizer.nextToken();

							// Try to convert the two operands into ints 
							// (if it can't be done, throw a NumberFormatException
					leftOperand  = Integer.parseInt(leftString);
					rightOperand = Integer.parseInt(rightString);


							// Try and perform the operation on the operands 
							// if it can't be done throw an ArithmeticException	

               if (operator.equals("+"))  // add the operands
						result = leftOperand + rightOperand;
					else
						if (operator.equals("%")) // find the remainder
						    result = leftOperand % rightOperand;
						else 
							if (operator.equals("/")) // obtain the quotient
								result = leftOperand / rightOperand;
							else 
								if (operator.equals("x")) // multiply the operands
									result = leftOperand * rightOperand;
								else 
									if (operator.equals("-")) // subtract the operands
										result = leftOperand - rightOperand;
									else  // invalid operator - set result to anything 
                           {
										result = leftOperand + rightOperand;
								   }

					return result;
		    }

}// end Calculator
