Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 10 additions & 3 deletions src/main/java/kyu5/ResistorColorCodes2.java
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Comment thread
krotname marked this conversation as resolved.
int[] resistorOhmsArr = encodeResistorOhmsToArr(resistorOhms);
return encodeResistorArrToColor(resistorOhmsArr);
} catch (IllegalArgumentException e) {
return "";
}
}

private static int encodeResistorOhms(String ohmsString) {
Expand All @@ -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);
}

Expand Down
3 changes: 3 additions & 0 deletions src/test/java/kyu5/ResistorColorCodes2Test.java
Original file line number Diff line number Diff line change
Expand Up @@ -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<Arguments> resistorCases() {
Expand Down