Java Quadratic equation solution

In algebra, a quadratic equation (from Latin quadratus ‘square‘) is any equation that can be rearranged in standard form as:

ax2 + bx + c = 0

This java program will try to find the roots of this quadratic equation based on the parameters a, b and c. This parameters are required to be given as input from the console and then the program show if there is root(s) (solutions) x1 and x2 for this equation.

There are three cases based on the values of the Discriminant (b2-4ac):

  • Positive Discriminant -> There are two roots x1 and x2 which are solution of the given equation
  • Discriminant is equal to Zero -> There is only one root x1 which is solution of the given equation
  • Negative Discriminant -> Then there are no real roots. Rather, there are two distinct (non-real) complex roots

More information about Quadratic equation

import java.util.Scanner;

public class QuadraticEquation {

    public static void main(String[] args) {
        // ax^2 + bx + c = 0
        int a, b, c;

        try(Scanner in = new Scanner(System.in))
        {
            System.out.println("Please give integer for a, b, and c: ");
            a = in.nextInt();
            b = in.nextInt();
            c = in.nextInt();
        }

        System.out.println("Now the program will try to find x roots ");
        System.out.println("For the Quadratic equation: ");
        System.out.format("%d*x^2+%d*x+%d=0", a, b, c );
        System.out.println();

        // Discriminant
        // b^2-4ac
        double d = Math.pow(b, 2) - 4*a*c;

        // find roots
        if(d > 1) {
            // Final find of distinct roots
            // x1 = (-b+√D)/2a    x2 = (-b-√D)/2a
            double x1 = (-b + Math.sqrt(d))/2*a;
            double x2 = (-b - Math.sqrt(d))/2*a;

            System.out.println("x1: " + x1);
            System.out.println("x2: " + x2);
        }
        else if(d == 0) {
            // both roots are real and equal
            double x1 = (-b + Math.sqrt(d))/2*a;
            System.out.println("Root is = "+ x1);
        }
        else {
            // roots are complex. They have real and imaginary part
            double real = -b / (2*a);
            double imaginary = Math.sqrt(-d) / (2*a);
            System.out.format("x1 = %f + i(%f)\n",
                    real, imaginary);
            System.out.format("x2 = %f - i(%f)\n",
                    real, imaginary);
        }

    }
}

Output:

1
7
-78
Now the program will try to find x roots 
For the Quadratic equation: 
1*x^2+7*b+-78=0
x1: 6.0
x2: -13.0

Leave a Comment

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

The reCAPTCHA verification period has expired. Please reload the page.