How to solve a Quadratic Equation using Java?

This post contains a program that will take take as input three values a, b and c of a quadratic equation and provide a solution.
This  program deals with all cases — no solution, only one root, multiple real roots and imaginary roots.

import java.util.Scanner;
public class QuadraticEquation {
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
System.out.println("Enter a,b and c");
double a=s.nextDouble();
double b=s.nextDouble();
double c=s.nextDouble();
if(a==0 && b==0)
{
System.out.println("No equation");
return;
}
if(a==0)
{
double root=-c/b;
System.out.println("Only one root " + root);
return;
}
double discr=b*b-4*a*c;
if(discr>=0)
{
discr=Math.sqrt(discr);
double root1=(-b + discr)/(2*a);
double root2=(-b - discr)/(2*a);
System.out.println("Two real roots");
System.out.println("x1=" + root1);
System.out.println("x2=" + root2);
return;
}
discr=Math.sqrt( -discr);
double realpart=-b/(2*a);
double imaginarypart=discr/(2*a);
System.out.println("Two complex roots");
System.out.println(realpart + " + i X " + imaginarypart);
System.out.println(realpart + " - i X " + imaginarypart);
}
}

 

Output

Enter a,b and c
1 2 3
Two complex roots
-1.0 + i X 1.4142135623730951
-1.0 – i X 1.4142135623730951

Output

Enter a,b and c
1 4 -8
Two real roots
x1=1.4641016151377544
x2=-5.464101615137754

1 thought on “How to solve a Quadratic Equation using Java?”

Leave a Reply