From 2b430714bb97b0cfd8fceb6b14078806d5d6e4eb Mon Sep 17 00:00:00 2001 From: Yadukrishnan Date: Wed, 10 Apr 2024 08:11:11 +0200 Subject: [PATCH] Added condition for divide by zero check --- .../com/baeldung/complexnumbers/ComplexNumber.java | 3 +++ .../ComplexNumberOperationsUnitTest.java | 11 +++++++++++ 2 files changed, 14 insertions(+) diff --git a/core-java-modules/core-java-numbers-7/src/main/java/com/baeldung/complexnumbers/ComplexNumber.java b/core-java-modules/core-java-numbers-7/src/main/java/com/baeldung/complexnumbers/ComplexNumber.java index 3283b081fe..223677b7e8 100644 --- a/core-java-modules/core-java-numbers-7/src/main/java/com/baeldung/complexnumbers/ComplexNumber.java +++ b/core-java-modules/core-java-numbers-7/src/main/java/com/baeldung/complexnumbers/ComplexNumber.java @@ -45,6 +45,9 @@ public record ComplexNumber(double real, double imaginary) { } 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 newReal = (this.real * that.real + this.imaginary * that.imaginary) / c2d2; double newImaginary = (this.imaginary * that.real - this.real * that.imaginary) / c2d2; diff --git a/core-java-modules/core-java-numbers-7/src/test/java/com/baeldung/complexnumbers/ComplexNumberOperationsUnitTest.java b/core-java-modules/core-java-numbers-7/src/test/java/com/baeldung/complexnumbers/ComplexNumberOperationsUnitTest.java index b3c95b7346..c92be1f877 100644 --- a/core-java-modules/core-java-numbers-7/src/test/java/com/baeldung/complexnumbers/ComplexNumberOperationsUnitTest.java +++ b/core-java-modules/core-java-numbers-7/src/test/java/com/baeldung/complexnumbers/ComplexNumberOperationsUnitTest.java @@ -1,6 +1,7 @@ package com.baeldung.complexnumbers; import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; @@ -86,6 +87,16 @@ public class ComplexNumberOperationsUnitTest { 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) { return result.real() == expected.real() && result.imaginary() == expected.imaginary(); }