Java program to convert octal number to decimal and vice versa

htt‮‬ps://www.theitroad.com

Here's a Java program to convert an octal number to decimal and vice-versa:

import java.util.Scanner;

public class OctalDecimalConverter {
    
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter a number:");
        String input = scanner.nextLine();
        if (input.startsWith("0")) {
            // Input is an octal number
            int decimal = octalToDecimal(input);
            System.out.println("Decimal equivalent of " + input + " is " + decimal);
        } else {
            // Input is a decimal number
            int octal = decimalToOctal(Integer.parseInt(input));
            System.out.println("Octal equivalent of " + input + " is " + octal);
        }
        scanner.close();
    }
    
    public static int octalToDecimal(String octal) {
        int decimal = 0;
        for (int i = 0; i < octal.length(); i++) {
            char c = octal.charAt(i);
            int digit = c - '0';
            decimal = decimal * 8 + digit;
        }
        return decimal;
    }
    
    public static int decimalToOctal(int decimal) {
        int octal = 0;
        int place = 1;
        while (decimal > 0) {
            int digit = decimal % 8;
            octal = octal + digit * place;
            place *= 10;
            decimal /= 8;
        }
        return octal;
    }
}

Explanation:

The main method reads user input using a Scanner object, and checks whether the input starts with the character '0'. If it does, it assumes the input is an octal number and converts it to decimal using the octalToDecimal method. Otherwise, it assumes the input is a decimal number and converts it to octal using the decimalToOctal method.

The octalToDecimal method takes an octal string as input, and uses a loop to iterate over each digit. It converts each digit to an integer, and multiplies the running decimal total by 8 before adding the current digit.

The decimalToOctal method takes a decimal integer as input, and uses a loop to convert it to an octal number. It repeatedly calculates the remainder when dividing by 8, and adds this to the output octal number multiplied by the appropriate power of 10. Finally, it updates the decimal number by dividing by 8.

Note that the program assumes that the user input is a valid octal or decimal number. If the input is invalid, the program may produce unexpected results or throw an exception.