What's new

Closed Quadratic equation

Status
Not open for further replies.

Bhadz141

Addict
Joined
Jun 1, 2016
Posts
30
Reaction
15
Points
81
// quadratic equation ax^2 + bx + c = 0

import java.util.*;

public class QuadraticEquation
{

// atributes are static so we can access them without creating object of QuadraticEquation class
// atributes are double so that we ensure precision
private static double a, b, c, x1, x2;
//sorry for using discriminant with "k" in it, its my native language and i dont feel like refacroring it all now :)
private static double diskriminant;

public static void main(String[] args) {

try {

//user imput
Scanner input = new Scanner(System.in);

System.out.println("enter a");
a = input.nextDouble();

System.out.println("enter b");
b = input.nextDouble();

System.out.println("enter c");
c = input.nextDouble();

// count discriminant
diskriminant = countDiskriminant(a, b, c);

// count solution
countSolution(a, b, c, diskriminant);

// not forgeting to close the Scanner
input.close();

// in case someone enters String
} catch (Exception e){
System.out.println("Input Error. :-(");
}

}


// static method for discriminant
public static double countDiskriminant(double a, double b, double c) {

double diskriminant = (b * b) - (4 * a * c);
return diskriminant;

}


// method for solution, using if for all three cases of discriminant
public static void countSolution (double a, double b, double c, double diskriminant) {

// no solution
if (diskriminant < 0) {
System.out.println("There is no solution in real numbers. :-(");
// one dual solution
} else if (diskriminant == 0) {
x1 = -b / 2 * a;
x2 = -b / 2 * a;

System.out.println("there is one dual solution");
System.out.println("x1 = " + x1);
System.out.println("x2 = " + x2);

// regular solution
} else {
x1 = (-b + Math.sqrt(diskriminant)) / (2 * a);
x2 = (-b - Math.sqrt(diskriminant)) / (2 * a);

System.out.println("solutions are:");
System.out.println("x1 = " + x1);
System.out.println("x2 = " + x2);
}
}
}
 
Status
Not open for further replies.

Similar threads

Back
Top