home *** CD-ROM | disk | FTP | other *** search
/ Java Certification Exam Guide / McGrawwHill-JavaCertificationExamGuide.iso / pc / Web Links and Code / ans / chap8 / exer0804 / Quad.java
Encoding:
Java Source  |  1997-04-20  |  1.0 KB  |  34 lines

  1. class Quad {
  2.    public static void main(String[] args) {
  3.       Quad q = new Quad();
  4.       try {
  5.          // WORKS double[] answer = q.roots(1.2, 3.2, -4.0);
  6.          double[] answer = q.roots(1.2, 0.0, 2.1); // Produces exception
  7.          System.out.println("The roots are " +
  8.             answer[0] + ", " + answer[1]);
  9.       } catch (NoRootsException x) {
  10.          System.out.println("No roots exist: " + x.getMessage());
  11.       }
  12.    }
  13.  
  14.    double[] roots(double a, double b, double c) throws NoRootsException {
  15.       double[] result = new double[2];
  16.       double temp = (b * b) - ( 4 * a * c);
  17.       if (temp < 0)
  18.          throw new NoRootsException("negative square root");
  19.       if (a < 0)
  20.          throw new NoRootsException("divide by zero");
  21.       temp = Math.sqrt(temp);
  22.       result[0] = (- b + temp) / (2.0 * a);
  23.       result[1] = (- b - temp) / (2.0 * a);
  24.       return result;
  25.    }
  26.       
  27. }
  28.  
  29. class NoRootsException extends Exception {
  30.    NoRootsException(String s) {
  31.       super(s);
  32.    }
  33. }
  34.