A Java code for computing the roots of a quadratic equation
Below is an example of a Java code that solves a quadratic equation. The code contains instances where the equation reduces to a linear equation, has no solution, or has infinite solutions.
// JAVA CODE import java.util.*; // Import the Scanner class and printf import java.lang.Math; // To use sqrt() and abs() methods class quadratic { public static void main(String[] args) { Scanner userIn = new Scanner(System.in); // Create a Scanner object System.out.println("Solving quadratic equation: ax^2 + bx +c = 0"); // Ask user input the value of a, b, and c System.out.println("Enter a: "); double a = userIn.nextDouble(); System.out.println("Enter b: "); double b = userIn.nextDouble(); System.out.println("Enter c: "); double c = userIn.nextDouble(); // solving the equation if (a == 0.0) { if (b == 0.0) { if (c != 0) { System.out.println("The equation has no solutions"); } else { System.out.println("The equation has infinite solutions"); } } else { double x1 = -c/b; System.out.printf("The equation is linear and has one root, which is %.2f\n",x1); } } else { double delta = b*b - 4*a*c; if (delta == 0.0) { double x1 = -b/(2*a); System.out.printf("The equation has one unique real root, which is %.2f\n",x1); } else if (delta > 0.0) { double x1 = (-b - Math.sqrt(delta))/(2*a); double x2 = (-b + Math.sqrt(delta))/(2*a); System.out.printf("The equation has two real roots, which is %.2f and %.2f\n",x1,x2); } else if (delta < 0.0) { double realx = -b/(2*a); double imx = (Math.sqrt(Math.abs(delta))) / (2*a); System.out.println("The equation has two conjugate complex roots"); System.out.printf("x1 = %.2f - i(%.2f)\n", realx, Math.abs(imx)); System.out.printf("x2 = %.2f + i(%.2f)\n", realx, Math.abs(imx) ); } } } }