|
| 1 | +package practice; |
| 2 | + |
| 3 | +import java.util.Scanner; |
| 4 | + |
| 5 | +public class QuadraticEquation { |
| 6 | + |
| 7 | + public static void main(String[] args) { |
| 8 | + |
| 9 | + System.out.println("Program to find real values for a Quadratic Equation.\n---"); |
| 10 | + |
| 11 | + Scanner sm = new Scanner(System.in); |
| 12 | + System.out.println("Enter the integer values of a, b and c as for equation = ax2 + bx+ c:"); |
| 13 | + int a,b,c; |
| 14 | + |
| 15 | + System.out.print("a: "); |
| 16 | + a= sm.nextInt(); |
| 17 | + System.out.print("b: "); |
| 18 | + b= sm.nextInt(); |
| 19 | + System.out.print("c: "); |
| 20 | + c= sm.nextInt(); |
| 21 | + |
| 22 | + sm.close(); |
| 23 | + |
| 24 | + double d=discriminant(a,b,c); |
| 25 | + |
| 26 | + if (d>0) { |
| 27 | + System.out.println("D > 0\n2 Real Solutions."); |
| 28 | + //if discriminant is real; |
| 29 | + findRealValues(a,b,c,d); |
| 30 | + } |
| 31 | + |
| 32 | + else if (d==0) { |
| 33 | + System.out.println("1 Real Solution."); |
| 34 | + //if discriminant is real; |
| 35 | + findRealValues(a,b,c,d); |
| 36 | + } |
| 37 | + |
| 38 | + else if (d<0) { |
| 39 | + System.out.println("D < 0\n2 Imaginary Solutions."); |
| 40 | + System.out.println("Cannot perform calculation as there are no Real Solutions."); |
| 41 | + end(); |
| 42 | + } |
| 43 | + |
| 44 | + else { |
| 45 | + System.out.println("Unknown Error"); |
| 46 | + end(); |
| 47 | + } |
| 48 | + |
| 49 | + } |
| 50 | + |
| 51 | + private static double discriminant(int a, int b, int c) { |
| 52 | + |
| 53 | + double d = ((b*b)-(4*a*c)); |
| 54 | + System.out.println("D = "+d); |
| 55 | + return d; |
| 56 | + } |
| 57 | + |
| 58 | + private static void findRealValues(int a, int b, int c, double d) { |
| 59 | + |
| 60 | + String ss = ""; |
| 61 | + |
| 62 | + double x1= (((-b)+(Math.sqrt(d)))/(2*a)); |
| 63 | + double x2= (((-b)-(Math.sqrt(d)))/(2*a)); |
| 64 | + |
| 65 | + ss = ss + x1 + ", " +x2; |
| 66 | + System.out.println("Answer: "+ ss); |
| 67 | + |
| 68 | + end(); |
| 69 | + } |
| 70 | + |
| 71 | + |
| 72 | + private static void end() { |
| 73 | + System.out.println("---\nThe Program has ended."); |
| 74 | + System.exit(0); |
| 75 | + } |
| 76 | + |
| 77 | + |
| 78 | +} |
0 commit comments