Repository: TheAlgorithms/Java
Pull request #5345 (2024-08-18 14:53:18)

refactor: `OctalToHexadecimal`
Improving readability.
Adding tests.

<!--
Thank you for your contribution!
In order to reduce the number of notifications sent to the maintainers, please:
- create your PR as draft, cf. https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/about-pull-requests#draft-pull-requests,
- make sure that all of the CI checks pass,
- mark your PR as ready for review, cf. https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/changing-the-stage-of-a-pull-request#marking-a-pull-request-as-ready-for-review
-->

<!-- For completed items, change [ ] to [x] -->

- [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Java/blob/master/CONTRIBUTING.md).
- [x] This pull request is all my own work -- I have not plagiarized it.
- [x] All filenames are in PascalCase.
- [x] All functions and variable names follow Java naming conventions.
- [x] All new algorithms have a URL in their comments that points to Wikipedia or other similar explanations.
- [x] All new code is formatted with `clang-format -i --style=file path/to/your/file.java`

codecov-commenter: ## [Codecov](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5345?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms) Report
Attention: Patch coverage is `88.88889%` with `2 lines` in your changes missing coverage. Please review.
> Project coverage is 43.29%. Comparing base [(`404ad72`)](https://app.codecov.io/gh/TheAlgorithms/Java/commit/404ad7272f18c8e48b5c65c69e117b449ea553c6?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms) to head [(`d9a6afa`)](https://app.codecov.io/gh/TheAlgorithms/Java/commit/d9a6afacbb0c27f99a6411b0df8d052e3deecf9e?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms).

| [Files](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5345?dropdown=coverage&src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms) | Patch % | Lines |
|---|---|---|
| [.../thealgorithms/conversions/OctalToHexadecimal.java](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5345?src=pr&el=tree&filepath=src%2Fmain%2Fjava%2Fcom%2Fthealgorithms%2Fconversions%2FOctalToHexadecimal.java&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms#diff-c3JjL21haW4vamF2YS9jb20vdGhlYWxnb3JpdGhtcy9jb252ZXJzaW9ucy9PY3RhbFRvSGV4YWRlY2ltYWwuamF2YQ==) | 88.88% | [0 Missing and 2 partials :warning: ](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5345?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms) |

<details><summary>Additional details and impacted files</summary>


```diff
@@             Coverage Diff              @@
##             master    #5345      +/-   ##
============================================
+ Coverage     43.27%   43.29%   +0.01%     
- Complexity     2681     2683       +2     
============================================
  Files           522      522              
  Lines         15456    15450       -6     
  Branches       2952     2952              
============================================
  Hits           6689     6689              
+ Misses         8481     8473       -8     
- Partials        286      288       +2     
```

</details>

[:umbrella: View full report in Codecov by Sentry](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5345?dropdown=coverage&src=pr&el=continue&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms).   
:loudspeaker: Have feedback on the report? [Share it here](https://about.codecov.io/codecov-pr-comment-feedback/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms).


Patch:
diff --git a/src/main/java/com/thealgorithms/conversions/OctalToHexadecimal.java b/src/main/java/com/thealgorithms/conversions/OctalToHexadecimal.java
index 5cc97fde..bac56dc2 100644
--- a/src/main/java/com/thealgorithms/conversions/OctalToHexadecimal.java
+++ b/src/main/java/com/thealgorithms/conversions/OctalToHexadecimal.java
@@ -1,65 +1,61 @@
 package com.thealgorithms.conversions;
 
-import java.util.Scanner;
-
 /**
- * Converts any Octal Number to HexaDecimal
+ * Class for converting an Octal number to its Hexadecimal equivalent.
  *
  * @author Tanmay Joshi
  */
 public final class OctalToHexadecimal {
+    private static final int OCTAL_BASE = 8;
+    private static final int HEX_BASE = 16;
+    private static final String HEX_DIGITS = "0123456789ABCDEF";
+
     private OctalToHexadecimal() {
     }
 
     /**
-     * This method converts a Octal number to a decimal number
+     * Converts an Octal number (as a string) to its Decimal equivalent.
      *
-     * @param s The Octal Number
-     * @return The Decimal number
+     * @param octalNumber The Octal number as a string
+     * @return The Decimal equivalent of the Octal number
+     * @throws IllegalArgumentException if the input contains invalid octal digits
      */
-    public static int octToDec(String s) {
-        int i = 0;
-        for (int j = 0; j < s.length(); j++) {
-            char num = s.charAt(j);
-            num -= '0';
-            i *= 8;
-            i += num;
+    public static int octalToDecimal(String octalNumber) {
+        if (octalNumber == null || octalNumber.isEmpty()) {
+            throw new IllegalArgumentException("Input cannot be null or empty");
         }
-        return i;
+
+        int decimalValue = 0;
+        for (int i = 0; i < octalNumber.length(); i++) {
+            char currentChar = octalNumber.charAt(i);
+            if (currentChar < '0' || currentChar > '7') {
+                throw new IllegalArgumentException("Incorrect octal digit: " + currentChar);
+            }
+            int currentDigit = currentChar - '0';
+            decimalValue = decimalValue * OCTAL_BASE + currentDigit;
+        }
+
+        return decimalValue;
     }
 
     /**
-     * This method converts a Decimal number to a Hexadecimal number
+     * Converts a Decimal number to its Hexadecimal equivalent.
      *
-     * @param d The Decimal Number
-     * @return The Hexadecimal number
+     * @param decimalNumber The Decimal number
+     * @return The Hexadecimal equivalent of the Decimal number
      */
-    public static String decimalToHex(int d) {
-        String digits = "0123456789ABCDEF";
-        if (d <= 0) {
+    public static String decimalToHexadecimal(int decimalNumber) {
+        if (decimalNumber == 0) {
             return "0";
         }
-        String hex = "";
-        while (d > 0) {
-            int digit = d % 16;
-            hex = digits.charAt(digit) + hex;
-            d = d / 16;
-        }
-        return hex;
-    }
 
-    public static void main(String[] args) {
-        Scanner input = new Scanner(System.in);
-        System.out.print("Enter the Octal number: ");
-        // Take octal number as input from user in a string
-        String oct = input.next();
-
-        // Pass the octal number to function and get converted decimal form
-        int decimal = octToDec(oct);
+        StringBuilder hexValue = new StringBuilder();
+        while (decimalNumber > 0) {
+            int digit = decimalNumber % HEX_BASE;
+            hexValue.insert(0, HEX_DIGITS.charAt(digit));
+            decimalNumber /= HEX_BASE;
+        }
 
-        // Pass the decimal number to function and get converted Hex form of the number
-        String hex = decimalToHex(decimal);
-        System.out.println("The Hexadecimal equivalant is: " + hex);
-        input.close();
+        return hexValue.toString();
     }
 }


Test patch:
diff --git a/src/test/java/com/thealgorithms/conversions/OctalToHexadecimalTest.java b/src/test/java/com/thealgorithms/conversions/OctalToHexadecimalTest.java
index f71732b2..6f2ccc24 100644
--- a/src/test/java/com/thealgorithms/conversions/OctalToHexadecimalTest.java
+++ b/src/test/java/com/thealgorithms/conversions/OctalToHexadecimalTest.java
@@ -1,14 +1,23 @@
 package com.thealgorithms.conversions;
 
-import static org.junit.jupiter.api.Assertions.assertEquals;
-
-import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.CsvSource;
 
 public class OctalToHexadecimalTest {
 
-    @Test
-    public void testOctalToHexadecimal() {
-        assertEquals("1EA", OctalToHexadecimal.decimalToHex(OctalToHexadecimal.octToDec("752")));
-        assertEquals("15E", OctalToHexadecimal.decimalToHex(OctalToHexadecimal.octToDec("536")));
+    @ParameterizedTest
+    @CsvSource({"0, 0", "7, 7", "10, 8", "17, F", "20, 10", "777, 1FF", "1234, 29C", "752, 1EA", "536, 15E"})
+    void testCorrectInputs(String inputOctal, String expectedHex) {
+        int decimal = OctalToHexadecimal.octalToDecimal(inputOctal);
+        String hex = OctalToHexadecimal.decimalToHexadecimal(decimal);
+        Assertions.assertEquals(expectedHex, hex);
+    }
+
+    @ParameterizedTest
+    @CsvSource({"'', Input cannot be null or empty", "'8', Incorrect octal digit: 8", "'19', Incorrect octal digit: 9"})
+    void testIncorrectInputs(String inputOctal, String expectedMessage) {
+        IllegalArgumentException exception = Assertions.assertThrows(IllegalArgumentException.class, () -> OctalToHexadecimal.octalToDecimal(inputOctal));
+        Assertions.assertEquals(expectedMessage, exception.getMessage());
     }
 }