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
Note: Could you plz go through this code and let me
know if u need any changes in this.Thank You
_________________
// DecimalToOctal.java
import java.util.Scanner;
public class DecimalToOctal {
public static void main(String[] args) {
int decimal,octal;
String octalStr="",str="";
/*
* Creating an Scanner class object
which is used to get the inputs
* entered by the user
*/
Scanner sc = new
Scanner(System.in);
System.out.print("Please enter a
number between 0 and 2097151 :");
decimal=sc.nextInt();
if(decimal<0 ||
decimal>2097151)
{
System.out.println("UNABLE TO CONVERT");
}
else
{
octal=decimalToOctal(decimal);
if(String.valueOf(octal).length()<7)
{
for(int
i=0;i<7-String.valueOf(octal).length();i++)
{
str+="0";
}
}
System.out.println("Your integer number "+decimal+" is
"+str+""+octal+" in octal.");
}
}
//This function will convert decimal to octal
form
public static int decimalToOctal(int
decimal_num)
{
int rem=0;
int octal=0;
String str="";
while(decimal_num!=0)
{
rem=decimal_num%8;
str+=rem;
decimal_num=decimal_num/8;
}
String rev="";
for(int i=str.length()-1;i>=0;i--)
{
rev=rev+str.charAt(i);
}
return Integer.parseInt(rev);
}
}
__________________
Output:
Please enter a number between 0 and 2097151
:160000
Your integer number 160000 is 0470400 in
octal.
__________________
Output#2:
Please enter a number between 0 and 2097151
:5000000
UNABLE TO CONVERT
_______________Could you plz rate me well.Thank You