CS1103 Exercise Unit 1 - Calculate the root of a quadratic equation

Questions

Write a program that allows the user to specify values for A, B, and C, and returns the larger of the two roots of a quadratic equation A*x*x + B*x + C = 0. Simultaneously, if an error occurs, the program should catch that error and print an error message.

1. Codes

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import java.util.Scanner;

/**
* SolveEquations allows the user to specify values for A, B, and C,
* and returns the larger of the two roots of a quadratic equation A*x*x + B*x + C = 0.
*
* @author Zhiyao He
*/
public class SolveEquations {
/**
* a, b, c are the values of A, B, C entered by the user.
* solution is the root of the quadratic equation.
*/
public static double a;
public static double b;
public static double c;
public static double solution;

/**
* Returns the larger of the two roots of the quadratic equation
* A*x*x + B*x + C = 0, provided it has any roots. If A == 0 or
* if the discriminant, B*B - 4*A*C, is negative, then an exception
* of type IllegalArgumentException is thrown.
*/
public static double root(double A, double B, double C) throws IllegalArgumentException {
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);
}
}

/**
* Get the values of A, B, and C, then compute the root.
* The program will continue until the user enters no.
*
* @param args
*/
public static void main(String[] args) {
try (Scanner in = new Scanner(System.in)) {
while (true) {
System.out.println("Please enter A: ");
a = in.nextDouble();

System.out.println("Please enter B: ");
b = in.nextDouble();

System.out.println("Please enter C: ");
c = in.nextDouble();

// compute a solution of the equation.
try {
solution = root(a, b, c);
System.out.println("The root is: " + solution);
} catch (IllegalArgumentException e) {
System.out.println("IllegalArgumentException: " + e.getMessage());
}

// The program will continue until the user answers no.
System.out.println("Would you like to enter another equation? Please enter yes/no:");
String s = in.next();
if (s.equals("no")) {
System.out.println("Goodbye!");
break;
}
}
}
}
}

2. Outputs:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
Please enter A: 
1.0
Please enter B:
2.0
Please enter C:
1.0
The root is: -1.0
Would you like to enter another equation? Please enter yes/no:
yes
Please enter A:
5.0
Please enter B:
2.0
Please enter C:
3.0
IllegalArgumentException: Discriminant < zero.
Would you like to enter another equation? Please enter yes/no:
no
Goodbye!

Process finished with exit code 0

​


This is the ending, thanks for reading.