package com.mycompany.mavenproject1;
import java.util.Scanner;
public class Mavenproject1 {
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
double a, b, c;
double x1, x2;
System.out.println("Ingresa el valor de a: ");
a = sc.nextDouble();
System.out.println("Ingresa el valor de b: ");
b = sc.nextDouble();
System.out.println("Ingresa el valor de c: ");
c = sc.nextDouble();
try {
x1 = ((-b) - (Math.sqrt(Math.pow(b, 2) - 4 * a * c))) / 2 * a;
x2 = ((-b) (Math.sqrt(Math.pow(b, 2) - 4 * a * c))) / 2 * a;
System.out.println("x1: " x1 ", x2: " x2);
} catch (Exception e) {
System.out.println("Hay un problema");
}
}
}
CodePudding user response:
Arithmetic with double
values does not throw exceptions. Nor does taking a square root of zero or a negative number. So your code going to have to test for specific inputs (or results) and throw an exception explicitly.
Hints:
read the javadocs for
Math.sqrt(double)
andDouble.isNaN(double)
read about what
NaN
means in floating point arithmetic,read about √-1 and complex numbers (if you have forgotten your high-school math classes),
do some algebra to figure out what values cause the quadratic formula to produce complex numbers as the "roots".
CodePudding user response:
B is value to get square root from answer , then you want to throw exception.
Example: √0^2 = 0, then yeah not divisible.
Solution:
use If-else statement and throw exceptions(custom or default).
//If square root B is 0, then Throw error
try {
if(b == 0){
throw new Exception();
}
else {
x1 = ((-b) - (Math.sqrt(Math.pow(b, 2) - 4 * a * c))) / 2 * a;
x2 = ((-b) (Math.sqrt(Math.pow(b, 2) - 4 * a * c))) / 2 * a;
System.out.println("x1: " x1 ", x2: " x2);
}
} catch (Exception e) {
System.out.println("There is A Problem");
}
I replicated It, and this is bonus for you: https://onlinegdb.com/9oqNMLySU
Give a thumbs up if it helps. Gladge
CodePudding user response:
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
int a, b, c;
int x1, x2, divisor, dividendo1, dividendo2, raiz, resta, cuadrado;
System.out.println("Ingresa el valor de a: ");
a = sc.nextInt();
System.out.println("Ingresa el valor de b: ");
b = sc.nextInt();
System.out.println("Ingresa el valor de c: ");
c = sc.nextInt();
cuadrado = b * b;
resta = cuadrado - 4 * a * c;
raiz = (int)Math.sqrt(resta);
if (raiz==0) {
throw new ArithmeticException();
}
dividendo1 = -b - raiz;
dividendo2 = -b raiz;
divisor = 2 * a;
x1 = dividendo1 / divisor;
x2 = dividendo2 / divisor;
System.out.println("x1: " x1 ", x2: " x2);
}
}
I got it!