In: Computer Science
Write a Java program to convert decimal (integer) numbers into their octal number (integer) equivalents. The input to the program will be a single non-negative integer number. If the number is less than or equal to 2097151, convert the number to its octal equivalent.
If the number is larger than 2097151, output the phrase “UNABLE TO CONVERT” and quit the program.
The output of your program will always be a 7-digit octal number with no spaces between any of the digits. Some of the leading digits may be 0.
Use a while loop to solve the problem. Do not use strings.
Sample Program Run
Please enter a number between 0 and 2097151 to convert:
160000
Your integer number 160000 is 0470400 in octal.
Please enter a number between 0 and 2097151 to convert:
5000000
UNABLE TO CONVERT
import java.util.Scanner; public class DecimalToOctal { public static void main(String[] args) { Scanner in = new Scanner(System.in); while (true) { System.out.print("Please enter a number between 0 and 2097151 to convert: "); int n = in.nextInt(); if (n < 0 || n > 2097151) { System.out.println("UNABLE TO CONVERT"); break; } int num = n; String total = ""; while (n > 0) { total = n % 8 + total; n /= 8; } System.out.printf("Your integer number %d is %" + (7-total.length()) + "d%s in octal.\n", num, 0, total); } } }