diff --git a/src/main/java/kyu5/ResistorColorCodes2.java b/src/main/java/kyu5/ResistorColorCodes2.java index 01522d8..b627ed0 100644 --- a/src/main/java/kyu5/ResistorColorCodes2.java +++ b/src/main/java/kyu5/ResistorColorCodes2.java @@ -9,9 +9,13 @@ public class ResistorColorCodes2 { public static String encodeResistorColors(String ohmsString) { if (ohmsString == null || !ohmsString.endsWith(" ohms")) return ""; - int resistorOhms = encodeResistorOhms(ohmsString); - int[] resistorOhmsArr = encodeResistorOhmsToArr(resistorOhms); - return encodeResistorArrToColor(resistorOhmsArr); + try { + int resistorOhms = encodeResistorOhms(ohmsString); + int[] resistorOhmsArr = encodeResistorOhmsToArr(resistorOhms); + return encodeResistorArrToColor(resistorOhmsArr); + } catch (IllegalArgumentException e) { + return ""; + } } private static int encodeResistorOhms(String ohmsString) { @@ -22,6 +26,9 @@ private static int encodeResistorOhms(String ohmsString) { else if (tempArray[0].endsWith("M")) tempValue = parseDouble(tempArray[0].trim().substring(0, tempArray[0].length() - 1)) * 1_000_000; else tempValue = parseDouble(tempArray[0].trim()); + if (!Double.isFinite(tempValue) || tempValue < 10 || tempValue > 990_000_000) { + throw new IllegalArgumentException("Resistance must be between 10 and 990M ohms"); + } return (int) Math.round(tempValue); } diff --git a/src/test/java/kyu5/ResistorColorCodes2Test.java b/src/test/java/kyu5/ResistorColorCodes2Test.java index 26086c4..d8112bb 100644 --- a/src/test/java/kyu5/ResistorColorCodes2Test.java +++ b/src/test/java/kyu5/ResistorColorCodes2Test.java @@ -23,6 +23,9 @@ void shouldRejectMalformedInput() { assertEquals("", ResistorColorCodes2.encodeResistorColors(null)); assertEquals("", ResistorColorCodes2.encodeResistorColors("47")); assertEquals("", ResistorColorCodes2.encodeResistorColors("47 ohm")); + assertEquals("", ResistorColorCodes2.encodeResistorColors("abc ohms")); + assertEquals("", ResistorColorCodes2.encodeResistorColors("-1 ohms")); + assertEquals("", ResistorColorCodes2.encodeResistorColors("1e309 ohms")); } private static Stream resistorCases() {