Skip to content

Commit baadaab

Browse files
committed
Move ComplexNumberMultiply to maths package and add input validation with tests
1 parent e2a3cdb commit baadaab

File tree

2 files changed

+20
-6
lines changed

2 files changed

+20
-6
lines changed

src/main/java/com/thealgorithms/strings/ComplexNumberMultiply.java renamed to src/main/java/com/thealgorithms/maths/ComplexNumberMultiply.java

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,19 @@
1-
package com.thealgorithms.strings;
1+
package com.thealgorithms.maths;
22

33
/**
44
* Multiplies two complex numbers represented as strings in the form "a+bi".
5-
*
6-
* Example:
7-
* Input: 1+1i , 1+1i
8-
* Output: 0+2i
5+
* Supports negative values and validates input format.
96
*/
107
public final class ComplexNumberMultiply {
118

129
private ComplexNumberMultiply() {
1310
}
1411

1512
private static int[] parse(String num) {
13+
if (num == null || !num.matches("-?\\d+\\+-?\\d+i")) {
14+
throw new IllegalArgumentException("Invalid complex number format: " + num);
15+
}
16+
1617
String[] parts = num.split("\\+");
1718
int real = Integer.parseInt(parts[0]);
1819
int imaginary = Integer.parseInt(parts[1].replace("i", ""));

src/test/java/com/thealgorithms/strings/ComplexNumberMultiplyTest.java renamed to src/test/java/com/thealgorithms/maths/ComplexNumberMultiplyTest.java

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
1-
package com.thealgorithms.strings;
1+
package com.thealgorithms.maths;
22

33
import static org.junit.jupiter.api.Assertions.assertEquals;
4+
import static org.junit.jupiter.api.Assertions.assertThrows;
45

56
import org.junit.jupiter.api.Test;
67

@@ -20,4 +21,16 @@ void testNegative() {
2021
void testZero() {
2122
assertEquals("0+0i", ComplexNumberMultiply.multiply("0+0i", "5+3i"));
2223
}
24+
25+
@Test
26+
void testInvalidFormat() {
27+
assertThrows(IllegalArgumentException.class,
28+
() -> ComplexNumberMultiply.multiply("1+1", "1+1i"));
29+
}
30+
31+
@Test
32+
void testNullInput() {
33+
assertThrows(IllegalArgumentException.class,
34+
() -> ComplexNumberMultiply.multiply(null, "1+1i"));
35+
}
2336
}

0 commit comments

Comments
 (0)