Question:
How to convert a decimal to octal in java?
Answer:
This java code is based on the tutorial from:
http://www.wikihow.com/Convert-from-Decimal-to-Octal
http://www.wikihow.com/Convert-from-Decimal-to-Octal
Code:
public class DecimalToOctal { public static void main(String[] args) { int decimal = Integer.parseInt(args[0]); int results = decimal; int remainder = decimal; String octal = ""; while (results >= 8) { remainder = results % 8; results = results/8; octal = octal + remainder; } octal = octal + results; octal = new StringBuilder(octal).reverse().toString(); System.out.println ("Decimal : " + decimal); System.out.println ("Octal : " + octal); } }
Output:
$ java DecimalToOctal 9 Decimal : 9 Octal : 11 $ java DecimalToOctal 891 Decimal : 891 Octal : 1573 $ java DecimalToOctal 12345 Decimal : 12345 Octal : 30071