home *** CD-ROM | disk | FTP | other *** search
Java Source | 1997-04-20 | 1.0 KB | 34 lines |
- class Quad {
- public static void main(String[] args) {
- Quad q = new Quad();
- try {
- // WORKS double[] answer = q.roots(1.2, 3.2, -4.0);
- double[] answer = q.roots(1.2, 0.0, 2.1); // Produces exception
- System.out.println("The roots are " +
- answer[0] + ", " + answer[1]);
- } catch (NoRootsException x) {
- System.out.println("No roots exist: " + x.getMessage());
- }
- }
-
- double[] roots(double a, double b, double c) throws NoRootsException {
- double[] result = new double[2];
- double temp = (b * b) - ( 4 * a * c);
- if (temp < 0)
- throw new NoRootsException("negative square root");
- if (a < 0)
- throw new NoRootsException("divide by zero");
- temp = Math.sqrt(temp);
- result[0] = (- b + temp) / (2.0 * a);
- result[1] = (- b - temp) / (2.0 * a);
- return result;
- }
-
- }
-
- class NoRootsException extends Exception {
- NoRootsException(String s) {
- super(s);
- }
- }
-