import RootComputer;

/**
 * A simple way to test objects that can compute square roots.
 *
 * @author Samuel A. Rebelsky
 * @version 1.0 of October 1999
 */
public class RootTester {
  /**
   * Run a RootComputer on values given by the command line.
   * The structure of the values is
   *    num tolerance
   * Or
   *    num tolerance firstGuess
   */
  public boolean test(String[] args, RootComputer computer, SimpleOutput out) {
    // Have we encountered an error?
    boolean error = false;
    // Let the user know how to use this if it was started incorrectly.
    if ((args.length < 2) || (args.length > 3)) {
      return false;
    }
    // Set up the observer.
    SimpleOutput observer = null;
    // Get the number, tolerance, and guess
    double num = 0;
    double tol = 0;
    double guess = 1;
    try { num = (new Double(args[0])).doubleValue(); }
    catch (Exception e) {
      out.println("Error: '" + args[0] + "' is not a number.");
      error = true;
    }
    try { tol = (new Double(args[1])).doubleValue(); }
    catch (Exception e) {
      out.println("Error: '" + args[1] + "' is not a number.");
      error = true;
    }
    if (args.length == 3) {
      observer = out;
      try { guess = (new Double(args[2])).doubleValue(); }
      catch (Exception e) {
        out.println("Error: '" + args[2] + "' is not a number.");
        error = true;
      }
    } // is there a guess
    // Check valid values.
    if (num < 0) {
      out.println("Cannot compute square roots of negative numbers.");
      error = true;
    }
    if (tol <= 0) {
      out.println("Cannot compute square roots to that tolerance.");
      error = true;
    }
    // Has there been an error?  If so, stop.
    if (error) {
      return false;
    }
    else {
      double root = computer.sqrt(num, guess, tol, observer);
      out.println("The square root of " + num 
                  + " is approximately " + root);
      out.println(root + " squared is " + (root*root));
      return true;
    }
  } // test(String[], RootComputer)

} // class RootTester

