File tree Expand file tree Collapse file tree
main/java/com/thealgorithms/conversions
test/java/com/thealgorithms/conversions Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -14,6 +14,7 @@ private HexToOct() {
1414 *
1515 * @param hex The Hexadecimal number as a String.
1616 * @return The Decimal equivalent as an integer.
17+ * @throws IllegalArgumentException if the string contains a character that is not a hexadecimal digit
1718 */
1819 public static int hexToDecimal (String hex ) {
1920 String hexDigits = "0123456789ABCDEF" ;
@@ -23,6 +24,9 @@ public static int hexToDecimal(String hex) {
2324 for (int i = 0 ; i < hex .length (); i ++) {
2425 char hexChar = hex .charAt (i );
2526 int digitValue = hexDigits .indexOf (hexChar );
27+ if (digitValue == -1 ) {
28+ throw new IllegalArgumentException ("Invalid hexadecimal digit: " + hexChar );
29+ }
2630 decimalValue = 16 * decimalValue + digitValue ;
2731 }
2832
Original file line number Diff line number Diff line change 11package com .thealgorithms .conversions ;
22
33import static org .junit .jupiter .api .Assertions .assertEquals ;
4+ import static org .junit .jupiter .api .Assertions .assertThrows ;
45
56import org .junit .jupiter .api .Test ;
67
@@ -30,4 +31,11 @@ public void testHexToOctal() {
3031 assertEquals (0 , HexToOct .hexToOctal ("0" ));
3132 assertEquals (7777 , HexToOct .hexToOctal ("FFF" ));
3233 }
34+
35+ @ Test
36+ public void testInvalidHexDigitThrows () {
37+ assertThrows (IllegalArgumentException .class , () -> HexToOct .hexToDecimal ("1G" ));
38+ assertThrows (IllegalArgumentException .class , () -> HexToOct .hexToDecimal ("0x1A" ));
39+ assertThrows (IllegalArgumentException .class , () -> HexToOct .hexToOctal ("Z" ));
40+ }
3341}
You can’t perform that action at this time.
0 commit comments