Added condition for divide by zero check
This commit is contained in:
parent
423e60577d
commit
2b430714bb
@ -45,6 +45,9 @@ public record ComplexNumber(double real, double imaginary) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public ComplexNumber divide(ComplexNumber that) {
|
public ComplexNumber divide(ComplexNumber that) {
|
||||||
|
if(that.real == 0 && that.imaginary == 0 ){
|
||||||
|
throw new ArithmeticException("Division by 0 is now allowed!");
|
||||||
|
}
|
||||||
double c2d2 = Math.pow(that.real, 2) + Math.pow(that.imaginary, 2);
|
double c2d2 = Math.pow(that.real, 2) + Math.pow(that.imaginary, 2);
|
||||||
double newReal = (this.real * that.real + this.imaginary * that.imaginary) / c2d2;
|
double newReal = (this.real * that.real + this.imaginary * that.imaginary) / c2d2;
|
||||||
double newImaginary = (this.imaginary * that.real - this.real * that.imaginary) / c2d2;
|
double newImaginary = (this.imaginary * that.real - this.real * that.imaginary) / c2d2;
|
||||||
|
@ -1,6 +1,7 @@
|
|||||||
package com.baeldung.complexnumbers;
|
package com.baeldung.complexnumbers;
|
||||||
|
|
||||||
import org.junit.jupiter.api.Assertions;
|
import org.junit.jupiter.api.Assertions;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
import org.junit.jupiter.params.ParameterizedTest;
|
import org.junit.jupiter.params.ParameterizedTest;
|
||||||
import org.junit.jupiter.params.provider.CsvSource;
|
import org.junit.jupiter.params.provider.CsvSource;
|
||||||
|
|
||||||
@ -86,6 +87,16 @@ public class ComplexNumberOperationsUnitTest {
|
|||||||
Assertions.assertTrue(isSame(sum, expected));
|
Assertions.assertTrue(isSame(sum, expected));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void check_divide_by_zero() {
|
||||||
|
ComplexNumber complex1 = new ComplexNumber(1, 1);
|
||||||
|
ComplexNumber zero = new ComplexNumber(0, 0);
|
||||||
|
Exception exception = Assertions.assertThrows(ArithmeticException.class, () -> {
|
||||||
|
complex1.divide(zero);
|
||||||
|
});
|
||||||
|
Assertions.assertEquals(exception.getMessage(), "Division by 0 is now allowed!");
|
||||||
|
}
|
||||||
|
|
||||||
public boolean isSame(ComplexNumber result, ComplexNumber expected) {
|
public boolean isSame(ComplexNumber result, ComplexNumber expected) {
|
||||||
return result.real() == expected.real() && result.imaginary() == expected.imaginary();
|
return result.real() == expected.real() && result.imaginary() == expected.imaginary();
|
||||||
}
|
}
|
||||||
|
Loading…
x
Reference in New Issue
Block a user