From ef1a68fa6ad8aa17bd04312d5121c90546336ed9 Mon Sep 17 00:00:00 2001 From: CreeperKelten Date: Sun, 25 Feb 2024 14:27:51 -0800 Subject: [PATCH] Kelten Stowe --- .idea/misc.xml | 2 +- Java-Assignment-005.iml | 1 + src/Quadratic.java | 50 +++++++++++++++++++++++++++++++++++++++++ 3 files changed, 52 insertions(+), 1 deletion(-) create mode 100644 src/Quadratic.java diff --git a/.idea/misc.xml b/.idea/misc.xml index 639900d..172df7b 100644 --- a/.idea/misc.xml +++ b/.idea/misc.xml @@ -1,6 +1,6 @@ - + \ No newline at end of file diff --git a/Java-Assignment-005.iml b/Java-Assignment-005.iml index b46c0dd..e1006ff 100644 --- a/Java-Assignment-005.iml +++ b/Java-Assignment-005.iml @@ -5,6 +5,7 @@ + \ No newline at end of file diff --git a/src/Quadratic.java b/src/Quadratic.java new file mode 100644 index 0000000..13dc0ac --- /dev/null +++ b/src/Quadratic.java @@ -0,0 +1,50 @@ +import java.util.Scanner; + +public class Quadratic { + public static void main(String[] args) { + Scanner scanner = new Scanner(System.in); + + System.out.println("Enter the values of coefficients (a), (b), and (c) for the quadratic equation ax^2 + bx + c = 0:"); + + // Prompts the user to input a, b, and c + System.out.print("Enter the value of coefficient a: "); + double a = validateInput(scanner); + + System.out.print("Enter the value of coefficient b: "); + double b = validateInput(scanner); + + System.out.print("Enter the value of coefficient c: "); + double c = validateInput(scanner); + + // Calculates the discriminant + double discriminant = b * b - 4 * a * c; + + // Checks if the discriminant is non-negative + if (discriminant >= 0) { + // Calculate the two roots of the quadratic equation + double root1 = (-b + Math.sqrt(discriminant)) / (2 * a); + double root2 = (-b - Math.sqrt(discriminant)) / (2 * a); + + // Displays the roots + System.out.println("Root 1: " + root1); + System.out.println("Root 2: " + root2); + } else { + // Displays error message for imaginary roots + System.out.println("The roots are imaginary."); + } + + scanner.close(); + } + + // Validates the input and handle exceptions + private static double validateInput(Scanner scanner) { + while (true) { + try { + return Double.parseDouble(scanner.nextLine()); + } catch (NumberFormatException e) { + // Display error message for invalid input + System.out.println("Invalid input. Please enter a valid number."); + } + } + } +} \ No newline at end of file