Skip to content

Commit dc5842e

Browse files
committed
fix: handle Null Dereference in RomanToInteger
1 parent b849cbb commit dc5842e

File tree

3 files changed

+14
-3
lines changed

3 files changed

+14
-3
lines changed

.inferconfig

-1
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
{
22
"report-block-list-path-regex": [
33
"src/main/java/com/thealgorithms/ciphers/a5/CompositeLFSR.java",
4-
"src/main/java/com/thealgorithms/conversions/RomanToInteger.java",
54
"src/main/java/com/thealgorithms/datastructures/crdt/GCounter.java",
65
"src/main/java/com/thealgorithms/datastructures/crdt/PNCounter.java",
76
"src/main/java/com/thealgorithms/datastructures/graphs/KahnsAlgorithm.java",

src/main/java/com/thealgorithms/conversions/RomanToInteger.java

+6-2
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,10 @@ private RomanToInteger() {
1919
}
2020
};
2121

22+
private static int romanSymbolToInt(final char symbol) {
23+
return ROMAN_TO_INT.computeIfAbsent(symbol, c -> { throw new IllegalArgumentException("Unknown Roman symbol: " + c); });
24+
}
25+
2226
// Roman Number = Roman Numerals
2327

2428
/**
@@ -39,10 +43,10 @@ public static int romanToInt(String a) {
3943

4044
if (prev != ' ') {
4145
// checking current Number greater than previous or not
42-
newPrev = ROMAN_TO_INT.get(prev) > newPrev ? ROMAN_TO_INT.get(prev) : newPrev;
46+
newPrev = romanSymbolToInt(prev) > newPrev ? romanSymbolToInt(prev) : newPrev;
4347
}
4448

45-
int currentNum = ROMAN_TO_INT.get(c);
49+
int currentNum = romanSymbolToInt(c);
4650

4751
// if current number greater than prev max previous then add
4852
if (currentNum >= newPrev) {

src/test/java/com/thealgorithms/conversions/RomanToIntegerTest.java

+8
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package com.thealgorithms.conversions;
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

@@ -11,4 +12,11 @@ public void testRomanToInteger() {
1112
assertEquals(1994, RomanToInteger.romanToInt("MCMXCIV"));
1213
assertEquals(58, RomanToInteger.romanToInt("LVIII"));
1314
}
15+
16+
@Test
17+
void testRomanToIntegerThrows() {
18+
assertThrows(IllegalArgumentException.class, () -> RomanToInteger.romanToInt("Z"));
19+
assertThrows(IllegalArgumentException.class, () -> RomanToInteger.romanToInt("MZI"));
20+
assertThrows(IllegalArgumentException.class, () -> RomanToInteger.romanToInt("MMMO"));
21+
}
1422
}

0 commit comments

Comments
 (0)