import rebelsky.io.SimpleInput;
import rebelsky.io.SimpleOutput;

/**
 * A very simple calculator, intended as a sample solution for an
 * exercise in CS152 and as a test of my I/O package.
 * <p>
 * Copyright (c) 1998 Samuel A. Rebelsky.  All rights reserved.
 *
 * @author Samuel A. Rebelsky
 * @version 1.1 of February 1998
 */
public class Calculator 
{
  /**
   * Compute the effect of an operation on two integers.
   * <br>pre: The operation is "+", "-", "*", or "/".
   * <br>pre: The requested operation is legal (e.g., no division by 0).
   * <br>post: The appropriate value is returned.
   */
  public int compute(String op, int left, int right) 
  {
    if (op.equals("+")) {
      return left + right;
    }
    else if (op.equals("-")) {
      return left - right;
    }
    else if (op.equals("*")) {
      return left * right;
    }
    else if (op.equals("/")) {
      return left / right;
    }
    else {
      return 0;
    }
  } // compute

  /**
   * Repeatedly read expressions of the form VAL OP VAL and print
   * out the result.
   */
  public static void main(String[] args) {
    // The object used to read input.
    SimpleInput in = new SimpleInput();
    // The object used to write output.
    SimpleOutput out = new SimpleOutput();
    // The first value read.
    int left;
    // The second value read.
    int right;
    // The operation.
    String op;
    // A calculator that performs the computation.  Note that it is
    // possible for the main routine of a class to create an object
    // within that class.  This is a typical Java programming 
    // technique.
    Calculator calc = new Calculator();

    // Print an introduction.
    out.println("This is a simple calculator.  When prompted to do so,");
    out.println("enter an expression of the form OP VAL OP.  I will then");
    out.println("compute an answer.  Make sure to include a space around");
    out.println("your operation.");
    out.println();
    out.println("When you are done, hit control-D");
    
    // Prompt the user.
    out.print("Expression: ");
    // Keep going until they hit control-D (end of file)
    while (true) {
      if (in.eof()) break;
      // Read the left operand.
      left = in.readInt();
      if (in.eof()) break;
      // Read the operation
      op = in.readString();
      if (in.eof()) break;
      // Read the right operand.
      right = in.readInt();
      if (in.eof()) break;
      // Print out the expression
      out.print(left + " " + op + " " +  right + " = ");
      // And compute
      out.println(calc.compute(op,left,right));
      // Prompt the user.
      out.print("Expression: ");
    } // while
      
    // And we're done
    System.exit(0);
  } // main
} // Calculator

