How to solve a Quadratic Equation in Java

In this video, you will learn about how to solve quadratic equations in java Please do comment, likes, and share, and also don’t forget to subscribe for more cool videos. Thanks For Watching

import java.util.Scanner;

public class QuadraticEquationSolver {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.println("Enter the coefficients of the quadratic equation ax^2 + bx + c = 0");
        System.out.print("a: ");
        double a = scanner.nextDouble();
        System.out.print("b: ");
        double b = scanner.nextDouble();
        System.out.print("c: ");
        double c = scanner.nextDouble();

        double discriminant = b * b - 4 * a * c;

        if (discriminant < 0) {
            System.out.println("The quadratic equation has no real roots.");
        } else if (discriminant == 0) {
            double root = -b / (2 * a);
            System.out.printf("The quadratic equation has a single real root: %f", root);
        } else {
            double root1 = (-b + Math.sqrt(discriminant)) / (2 * a);
            double root2 = (-b - Math.sqrt(discriminant)) / (2 * a);
            System.out.printf("The quadratic equation has two real roots: %f and %f", root1, root2);
        }
    }
}

This program prompts the user to enter the coefficients of the quadratic equation, computes the discriminant, and then uses a series of conditional statements to determine the number and value(s) of the roots. Note that the Math.sqrt method is used to compute the square root of the discriminant.

Leave a Reply