From b4a54647ed453d5a69e6e9b629c971f190c7d247 Mon Sep 17 00:00:00 2001 From: Psycotik Date: Sun, 25 Feb 2024 00:49:40 -0800 Subject: [PATCH] Created Quadratic.java --- .idea/misc.xml | 2 +- .idea/vcs.xml | 6 ++++ Java-Assignment-005.iml | 1 + src/Quadratic.java | 64 +++++++++++++++++++++++++++++++++++++++++ 4 files changed, 72 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..69ace3f 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..2e8cd55 --- /dev/null +++ b/src/Quadratic.java @@ -0,0 +1,64 @@ +import java.util.Scanner; + +/** + * + * @author James Ward + * + * @since 02/25/2024 + * + */ + +public class Quadratic { + + public static void main(String[] args) { + + System.out.println("Enter positive integer values for variables a, b, and c in to calculate to roots of the quadratic equation ax^2 + bx + c = 0. Positive integers only."); + + // prompt for each variable + int a = userInput("a"); + int b = userInput("b"); + int c = userInput("c"); + + // calculate roots + double[] roots = quadraticEquation(a, b, c); + System.out.printf("The roots of the quadratic equation are: %.2f and %.2f%n", roots[0], roots[1]); + + } + + public static int userInput(String variableString) { + + Scanner in = new Scanner(System.in); + + System.out.println("Enter value for " + variableString + ": "); + + if (!in.hasNextInt()) { + String message = in.next(); + System.err.println("Input " + message + " is not a positive integer."); + return userInput(variableString); + } + + return in.nextInt(); + } + + public static double[] quadraticEquation(int a, int b, int c) { + + // check for division by zero + if (a == 0) { + System.err.println("Invalid input: 'a' can't be zero"); + } + + // calculate the discriminant + double discriminant = b * b - 4 * a * c; + + // check for negative discriminant + if (discriminant < 0) { + System.err.println("No real roots: Discriminant is negative"); + } + + // Calculate the solutions + double root1 = (-b + Math.sqrt(discriminant)) / (2 * a); + double root2 = (-b - Math.sqrt(discriminant)) / (2 * a); + + return new double[]{root1, root2}; + } +}