Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * @author: Joshua Gibbs
- * @title: ICA Ch. 11-1a
- * @date: 2/22/2017
- * @file: ICA11_1a.java
- * @class: CS 141 – Programming and Problem Solving
- * @purpose:
- * Write a program that has the following subroutine:
- *
- * static double root(double A, double B, double C)
- * throws IllegalArgumentException {
- * // Returns the larger of the two roots of
- * // the quadratic equation A*x*x + B*x + C = 0.
- * // (Throws an exception if A == 0 or B*B-4*A*C < 0.)
- * if (A == 0) {
- * throw new IllegalArgumentException("A can't be zero.");
- * }
- * else {
- * double disc = B*B - 4*A*C;
- * if (disc < 0)
- * throw new IllegalArgumentException("Discriminant < zero.");
- * return (-B + Math.sqrt(disc)) / (2*A);
- * }
- * }
- *
- * From within your main method for your program you should ask the user for three values.
- * Then you should call up our subroutine root and pass in the values given.
- * You should use a try catch block to handle any exceptions.
- * If a solution can be calculated for the three values, print out that solution.
- * If an exception is encountered, print out an error message.
- */
- import java.util.Scanner;
- public class ICA11_1a {
- public static void main (String[] args) {
- System.out.print("Please enter three space-separated numbers: ");
- Scanner in = new Scanner(System.in);
- double a = Double.parseDouble(in.next());
- double b = Double.parseDouble(in.next());
- double c = Double.parseDouble(in.next());
- try {
- System.out.println("Solution = " + root(a, b, c));
- } catch (IllegalArgumentException error) {
- System.out.println(error);
- }
- }
- static double root(double a, double b, double c) throws IllegalArgumentException {
- // Returns the larger of the two roots of
- // the quadratic equation a*x*x + b*x + c = 0.
- // (Throws an exception if a == 0 or b*b-4*a*c < 0.)
- if (a == 0) {
- throw new IllegalArgumentException("a can't be zero.");
- } else {
- double disc = b * b - 4 * a * c;
- if (disc < 0) {
- throw new IllegalArgumentException("Discriminant < zero.");
- }
- return (-b + Math.sqrt(disc)) / (2 * a);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement