Java Online Compiler
Example: Octal to Decimal Conversion in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// Octal to Decimal Conversion import java.util.Scanner; // Main class containing the entry point of the program public class Main { public static void main(String[] args) { // Step 1: Create a Scanner object to read user input Scanner scanner = new Scanner(System.in); // Step 2: Prompt the user to enter an octal number System.out.print("Enter an octal number: "); String octalString = scanner.nextLine(); // Step 3: Initialize variables for decimal equivalent and power of 8 int decimal = 0; int power = 0; // Step 4: Iterate through the octal string from right to left for (int i = octalString.length() - 1; i >= 0; i--) { // Step 5: Get the current digit as a character char digitChar = octalString.charAt(i); // Step 6: Convert the character digit to an integer // Subtract '0' to get the integer value of the digit int digit = digitChar - '0'; // Step 7: Check if the digit is valid for an octal number (0-7) if (digit < 0 || digit > 7) { System.out.println("Invalid octal number. Digits must be between 0 and 7."); scanner.close(); return; // Exit the program if invalid } // Step 8: Calculate the decimal equivalent for the current digit // digit * (8 ^ power) decimal += digit * Math.pow(8, power); // Step 9: Increment the power for the next digit power++; } // Step 10: Print the resulting decimal number System.out.println("Decimal equivalent: " + decimal); // Step 11: Close the scanner to prevent resource leaks scanner.close(); } }
Output
Clear
ADVERTISEMENTS