This Java code prompts the user to input values for variables A, B, and C to calculate the solution to a quadratic equation. It uses a try/catch block to handle exceptions from invalid inputs or a discriminant less than zero, and allows the user to retry entering values if an exception occurs. The root() method calculates the solution, throwing exceptions if A is zero or the discriminant is negative.
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0 ratings0% found this document useful (0 votes)
68 views1 page
CS 1103 Learning Journal Exercise 1
This Java code prompts the user to input values for variables A, B, and C to calculate the solution to a quadratic equation. It uses a try/catch block to handle exceptions from invalid inputs or a discriminant less than zero, and allows the user to retry entering values if an exception occurs. The root() method calculates the solution, throwing exceptions if A is zero or the discriminant is negative.
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 1
import java.util.
Scanner;
public class Main {
public static void main(String[] args) {
double A, B, C; double Solution; boolean Retry = false; Scanner scan = new Scanner(System.in); String next; do { System.out.println("Enter numbers for A, B, and C: "); System.out.println("A: "); A = scan.nextDouble(); System.out.println("B: "); B = scan.nextDouble(); System.out.println("C: "); C = scan.nextDouble(); try { Solution = root(A, B, C); System.out.println("A solution of the equation is " + Solution); break; } catch (IllegalArgumentException e) { System.out.println(e.getMessage() + "\n Do you wish to enter another equation? [Y/N]"); next = scan.next().toUpperCase(); if (next.equals("N")) break; else if (next.equals("Y")) Retry = true; else System.out.println("Invalid input."); } } while (Retry);
public static double root(double A, double B, double C) throws
IllegalArgumentException { if (A == 0) { throw new IllegalArgumentException("A can't be zero."); } else { double disc = B * B - 4 * A * C; if (disc < 0) throw new IllegalArgumentException("Discriminant < zero."); return (-B + Math.sqrt(disc)) / (2 * A); } } }