|
1 | 1 | package com.thealgorithms.conversions;
|
2 | 2 |
|
3 |
| -import java.util.Scanner; |
4 |
| - |
5 | 3 | /**
|
6 |
| - * Converts any Octal Number to a Decimal Number |
| 4 | + * Class for converting an octal number to a decimal number. Octal numbers are based on 8, using digits from 0 to 7. |
7 | 5 | *
|
8 |
| - * @author Zachary Jones |
9 | 6 | */
|
10 | 7 | public final class OctalToDecimal {
|
| 8 | + private static final int OCTAL_BASE = 8; |
| 9 | + |
11 | 10 | private OctalToDecimal() {
|
12 | 11 | }
|
13 | 12 |
|
14 | 13 | /**
|
15 |
| - * Main method |
| 14 | + * Converts a given octal number (as a string) to its decimal representation. |
| 15 | + * If the input is not a valid octal number (i.e., contains characters other than 0-7), |
| 16 | + * the method throws an IllegalArgumentException. |
16 | 17 | *
|
17 |
| - * @param args Command line arguments |
| 18 | + * @param inputOctal The octal number as a string |
| 19 | + * @return The decimal equivalent of the octal number |
| 20 | + * @throws IllegalArgumentException if the input is not a valid octal number |
18 | 21 | */
|
19 |
| - public static void main(String[] args) { |
20 |
| - Scanner sc = new Scanner(System.in); |
21 |
| - System.out.print("Octal Input: "); |
22 |
| - String inputOctal = sc.nextLine(); |
23 |
| - int result = convertOctalToDecimal(inputOctal); |
24 |
| - if (result != -1) { |
25 |
| - System.out.println("Result convertOctalToDecimal : " + result); |
| 22 | + public static int convertOctalToDecimal(String inputOctal) { |
| 23 | + if (inputOctal == null || inputOctal.isEmpty()) { |
| 24 | + throw new IllegalArgumentException("Input cannot be null or empty"); |
26 | 25 | }
|
27 |
| - sc.close(); |
28 |
| - } |
29 | 26 |
|
30 |
| - /** |
31 |
| - * This method converts an octal number to a decimal number. |
32 |
| - * |
33 |
| - * @param inputOctal The octal number |
34 |
| - * @return The decimal number |
35 |
| - */ |
36 |
| - public static int convertOctalToDecimal(String inputOctal) { |
37 |
| - try { |
38 |
| - // Actual conversion of Octal to Decimal: |
39 |
| - return Integer.parseInt(inputOctal, 8); |
40 |
| - } catch (NumberFormatException ne) { |
41 |
| - // Printing a warning message if the input is not a valid octal |
42 |
| - // number: |
43 |
| - System.out.println("Invalid Input, Expecting octal number 0-7"); |
44 |
| - return -1; |
| 27 | + int decimalValue = 0; |
| 28 | + |
| 29 | + for (int i = 0; i < inputOctal.length(); i++) { |
| 30 | + char currentChar = inputOctal.charAt(i); |
| 31 | + |
| 32 | + if (currentChar < '0' || currentChar > '7') { |
| 33 | + throw new IllegalArgumentException("Incorrect input: Expecting an octal number (digits 0-7)"); |
| 34 | + } |
| 35 | + |
| 36 | + int currentDigit = currentChar - '0'; |
| 37 | + decimalValue = decimalValue * OCTAL_BASE + currentDigit; |
45 | 38 | }
|
| 39 | + |
| 40 | + return decimalValue; |
46 | 41 | }
|
47 | 42 | }
|
0 commit comments