Home CPSC 220

Exceptions

 

Objective

To be able to use exceptions in programs.
 

Task

For this exercise, you will write a function which calculates the roots of a quadratic equation and returns them. Roots to equations are given by the quadratic formula:

For equations $y = ax^2 + bx + c$,

${x = \frac{{ - b\ \pm \sqrt {b^2 - 4ac} }}{{2a}}}$

The function should return the two roots (which may possibly be the same) in an array.

There are two exceptional situations that can occur:

  1. $a$ is zero, meaning the equation is not quadratic.
  2. the discriminant which is the $b^2 - 4ac$ part is negative, which means the quadratic has no real roots.

For both of these, you should throw IllegalArgumentException exceptions.

Your main function should read in a, b, and c from the user, then call the root finding function in a try block. If there are any exceptions, report them to the user.

Your main function should also keep prompting the user until they enter valid doubles for a, b, and c.


 

Example Run 1


Enter a, b, c: hello
For real put in a double!
3 4 5
There are no real roots!

 

Example Run 2


Enter a, b, c: 0 9 1
There are no real roots!

 

Example Run 3


Enter a, b, c: 3 -4 -5
Roots are 2.1196, and -0.7862.

 

Submitting

When your program works, email the code to ifinlay@umw.edu.

Copyright © 2024 Ian Finlayson | Licensed under a Attribution-NonCommercial 4.0 International License.