Skip to content

Commit 18f6f8c

Browse files
authored
fix: handle Null Dereference in RomanToInteger (#5461)
1 parent b849cbb commit 18f6f8c

File tree

3 files changed

+15
-8
lines changed

3 files changed

+15
-8
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-7
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) {
@@ -57,9 +61,4 @@ public static int romanToInt(String a) {
5761

5862
return sum;
5963
}
60-
61-
public static void main(String[] args) {
62-
int sum = romanToInt("MDCCCIV");
63-
System.out.println(sum);
64-
}
6564
}

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

+9
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

@@ -10,5 +11,13 @@ public class RomanToIntegerTest {
1011
public void testRomanToInteger() {
1112
assertEquals(1994, RomanToInteger.romanToInt("MCMXCIV"));
1213
assertEquals(58, RomanToInteger.romanToInt("LVIII"));
14+
assertEquals(1804, RomanToInteger.romanToInt("MDCCCIV"));
15+
}
16+
17+
@Test
18+
void testRomanToIntegerThrows() {
19+
assertThrows(IllegalArgumentException.class, () -> RomanToInteger.romanToInt("Z"));
20+
assertThrows(IllegalArgumentException.class, () -> RomanToInteger.romanToInt("MZI"));
21+
assertThrows(IllegalArgumentException.class, () -> RomanToInteger.romanToInt("MMMO"));
1322
}
1423
}

0 commit comments

Comments
 (0)