From b7a2b59f4e16725312f90f60e60550f1e44a8ab9 Mon Sep 17 00:00:00 2001 From: BFristoe Date: Sun, 25 Feb 2024 23:51:28 -0800 Subject: [PATCH] Created scanner input method created check for different roots --- .idea/misc.xml | 2 +- .idea/vcs.xml | 6 ++++++ Java-Assignment-005.iml | 1 + src/Quadratic.java | 43 +++++++++++++++++++++++++++++++++++++++++ 4 files changed, 51 insertions(+), 1 deletion(-) create mode 100644 .idea/vcs.xml 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/.idea/vcs.xml b/.idea/vcs.xml new file mode 100644 index 0000000..35eb1dd --- /dev/null +++ b/.idea/vcs.xml @@ -0,0 +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..b184b09 --- /dev/null +++ b/src/Quadratic.java @@ -0,0 +1,43 @@ +import java.util.Scanner; + +public class Quadratic { + + public static void main(String[] args) { + Scanner scanner = new Scanner(System.in); + + + // Prompt and validate input + double a = getInput(scanner, "a"); + double b = getInput(scanner, "b"); + double c = getInput(scanner, "c"); + + // Calculate discriminant + double split = b * b - 4 * a * c; + + // Check for different roots + if (split > 0) { + // Two real roots + double root1 = (-b + Math.sqrt(split)) / (2.0 * a); + double root2 = (-b - Math.sqrt(split)) / (2.0 * a); + System.out.printf("The roots are: %.2f and %.2f\n", root1, root2); + } else if (split == 0) { + // One real root + double root = -b / (2.0 * a); + System.out.printf("The root is: %.2f\n", root); + } else { + // No real roots + System.out.println("The equation has no real roots."); + } + + scanner.close(); // Close Scanner + } + + private static double getInput(Scanner scanner, String name) { + System.out.printf("Enter input for %s :", name); + while (!scanner.hasNextDouble()) { + System.out.printf("Invalid input for %s. Please enter an valid number: ", name); + scanner.next(); // Clear invalid input + } + return scanner.nextDouble(); + } +} \ No newline at end of file