Advertisement
Guest User

Untitled

a guest
Feb 22nd, 2017
50
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.27 KB | None | 0 0
  1. /**
  2. * @author: Joshua Gibbs
  3. * @title: ICA Ch. 11-1a
  4. * @date: 2/22/2017
  5. * @file: ICA11_1a.java
  6. * @class: CS 141 – Programming and Problem Solving
  7. * @purpose:
  8. * Write a program that has the following subroutine:
  9. *
  10. * static double root(double A, double B, double C)
  11. * throws IllegalArgumentException {
  12. * // Returns the larger of the two roots of
  13. * // the quadratic equation A*x*x + B*x + C = 0.
  14. * // (Throws an exception if A == 0 or B*B-4*A*C < 0.)
  15. * if (A == 0) {
  16. * throw new IllegalArgumentException("A can't be zero.");
  17. * }
  18. * else {
  19. * double disc = B*B - 4*A*C;
  20. * if (disc < 0)
  21. * throw new IllegalArgumentException("Discriminant < zero.");
  22. * return (-B + Math.sqrt(disc)) / (2*A);
  23. * }
  24. * }
  25. *
  26. * From within your main method for your program you should ask the user for three values.
  27. * Then you should call up our subroutine root and pass in the values given.
  28. * You should use a try catch block to handle any exceptions.
  29. * If a solution can be calculated for the three values, print out that solution.
  30. * If an exception is encountered, print out an error message.
  31. */
  32.  
  33. import java.util.Scanner;
  34.  
  35. public class ICA11_1a {
  36. public static void main (String[] args) {
  37. System.out.print("Please enter three space-separated numbers: ");
  38. Scanner in = new Scanner(System.in);
  39. double a = Double.parseDouble(in.next());
  40. double b = Double.parseDouble(in.next());
  41. double c = Double.parseDouble(in.next());
  42. try {
  43. System.out.println("Solution = " + root(a, b, c));
  44. } catch (IllegalArgumentException error) {
  45. System.out.println(error);
  46. }
  47. }
  48.  
  49. static double root(double a, double b, double c) throws IllegalArgumentException {
  50. // Returns the larger of the two roots of
  51. // the quadratic equation a*x*x + b*x + c = 0.
  52. // (Throws an exception if a == 0 or b*b-4*a*c < 0.)
  53. if (a == 0) {
  54. throw new IllegalArgumentException("a can't be zero.");
  55. } else {
  56. double disc = b * b - 4 * a * c;
  57. if (disc < 0) {
  58. throw new IllegalArgumentException("Discriminant < zero.");
  59. }
  60. return (-b + Math.sqrt(disc)) / (2 * a);
  61. }
  62. }
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement