In: Computer Science
Solve Quadratic Equation IN JAVA (static methods, parameters, arguments, Math functions)
Write a program that will print the real-valued solutions of a quadratic equation
ax^2+bx+c=0
For example:
Enter coefficient a: 1 Enter coefficient b: 10 Enter coefficient c: 2 The solutions are -0.2041684766872809, and -9.79583152331272
For another example:
Enter coefficient a: 1 Enter coefficient b: 2 Enter coefficient c: 3 The equation does not have real solution
The program should use the following methods.
b^2−4ac>=0
x = −b ± (√(b^2 − 4ac)) / (2a)
Notice that other than getCoeff() and the main() methods, methods should not interact with the user.
import java.util.Scanner;
public class Main {
public static double getCoeff(String msg) {
Scanner sc = new Scanner(System.in);
System.out.println(msg);
return sc.nextDouble();
}
public static boolean hasRealSolution(double a, double b, double c) {
return (b * b - 4 * a * c) >= 0;
}
public static double solution1(double a, double b, double c) {
return ((-1 * b) + (Math.sqrt(b * b - 4 * a * c))) / (2 *a);
}
public static double solution2(double a, double b, double c) {
return ((-1 * b) - (Math.sqrt(b * b - 4 * a * c))) / (2 * a);
}
public static void main(String[] args) {
double a = getCoeff("Enter coefficient a: ");
double b = getCoeff("Enter coefficient b: ");
double c = getCoeff("Enter coefficient c: ");
if (hasRealSolution(a, b, c)) {
System.out.println("The solutions are " + solution1(a, b, c) + ", and " + solution2(a, b, c));
} else {
System.out.println("The equation does not have real solution");
}
}
}