Skip to content

Commit fefbb9e

Browse files
committed
Validate resistor values before encoding
1 parent 7d7f849 commit fefbb9e

2 files changed

Lines changed: 13 additions & 3 deletions

File tree

src/main/java/kyu5/ResistorColorCodes2.java

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,9 +9,13 @@ public class ResistorColorCodes2 {
99

1010
public static String encodeResistorColors(String ohmsString) {
1111
if (ohmsString == null || !ohmsString.endsWith(" ohms")) return "";
12-
int resistorOhms = encodeResistorOhms(ohmsString);
13-
int[] resistorOhmsArr = encodeResistorOhmsToArr(resistorOhms);
14-
return encodeResistorArrToColor(resistorOhmsArr);
12+
try {
13+
int resistorOhms = encodeResistorOhms(ohmsString);
14+
int[] resistorOhmsArr = encodeResistorOhmsToArr(resistorOhms);
15+
return encodeResistorArrToColor(resistorOhmsArr);
16+
} catch (IllegalArgumentException e) {
17+
return "";
18+
}
1519
}
1620

1721
private static int encodeResistorOhms(String ohmsString) {
@@ -22,6 +26,9 @@ private static int encodeResistorOhms(String ohmsString) {
2226
else if (tempArray[0].endsWith("M"))
2327
tempValue = parseDouble(tempArray[0].trim().substring(0, tempArray[0].length() - 1)) * 1_000_000;
2428
else tempValue = parseDouble(tempArray[0].trim());
29+
if (!Double.isFinite(tempValue) || tempValue < 10 || tempValue > 990_000_000) {
30+
throw new IllegalArgumentException("Resistance must be between 10 and 990M ohms");
31+
}
2532
return (int) Math.round(tempValue);
2633
}
2734

src/test/java/kyu5/ResistorColorCodes2Test.java

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,9 @@ void shouldRejectMalformedInput() {
2323
assertEquals("", ResistorColorCodes2.encodeResistorColors(null));
2424
assertEquals("", ResistorColorCodes2.encodeResistorColors("47"));
2525
assertEquals("", ResistorColorCodes2.encodeResistorColors("47 ohm"));
26+
assertEquals("", ResistorColorCodes2.encodeResistorColors("abc ohms"));
27+
assertEquals("", ResistorColorCodes2.encodeResistorColors("-1 ohms"));
28+
assertEquals("", ResistorColorCodes2.encodeResistorColors("1e309 ohms"));
2629
}
2730

2831
private static Stream<Arguments> resistorCases() {

0 commit comments

Comments
 (0)