-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEquationSolver.java
51 lines (43 loc) · 1.58 KB
/
EquationSolver.java
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
/**
* Program for solving quadratic equations of view:
* a*x^2+b*x+c=0 where a,b,c represent polynomial coefficients
* Checks correctness of arguments ,then prints out roots or root of equation.
*/
public class EquationSolver {
public static void main(String[] args) {
solveEquation(1, 6, 9);
}
private static void solveEquation(double a, double b, double c) {
if (isEquationIncorrect(a)) {
System.out.println("Equation must be quadratic.\n Please check entered parameters and try again!");
} else {
double d = evaluateDiscriminant(a, b, c);
if (hasRoots(d)) {
yieldRoots(a, b, c, d);
} else {
System.out.println("Particularly this equation has no solution!");
}
}
}
//roots are defined iff D>=0;
private static boolean hasRoots(double d) {
return d >= 0;
}
private static void yieldRoots(double a, double b, double c, double d) {
if (d > 0) {
double x1 = ((-b) + Math.sqrt(d)) / (2 * a);
double x2 = ((-b) - Math.sqrt(d)) / (2 * a);
System.out.println("Roots of equation are \n" + "x1=" + x1 + "\n" + "x2=" + x2);
} else if (d == 0) {
double x = -b / (2 * a);
System.out.println("Equation has single root \n" + "x=" + x);
}
}
private static double evaluateDiscriminant(double a, double b, double c) {
double d = b * b - 4 * a * c;
return d;
}
private static boolean isEquationIncorrect(double a) {
return a == 0;
}
}