Chapter 5 Problem 37 Decimal to Binary Write a program that

Chapter 5 Problem 37 (Decimal to Binary)

Write a program that prompts the user to enter a decimal integer and displays its corresponding binary value. Don\'t use Java\'s Integer. toBinaryString(int) in this program. Hint: Program Plan. 1) Enter a decimal integer number. Do NOT use

public static StringBuffer toBinary(int number)
{
StringBuffer sb = new StringBuffer();
int t=0;
while(number>0)
{
t = number%2;
sb.append(t);
number = number / 2;
}

Solution

/* Note : if access specifier is specified as public then file name and class name should be same and main should be within that class only */ import java.util.*; import java.lang.*; import java.io.*; /* Name of the class has to be \"Main\" only if the class is public. */ class Dec_to_bin {    public static void main (String[] args) throws java.lang.Exception    { Dec_to_bin obj = new Dec_to_bin();    Scanner in = new Scanner(System.in); //Take User input from keyboard System.out.println(\"Enter decimal number: \"); int num = in.nextInt(); int bin =0; int i=0; while (num != 0) {    int d = num % 2; bin=bin+(d*((int)Math.pow(10,i))); num /= 2; i++; }    System.out.print(\"\ Binary representation is:\"); System.out.print(bin); System.out.println(); } }
Chapter 5 Problem 37 (Decimal to Binary) Write a program that prompts the user to enter a decimal integer and displays its corresponding binary value. Don\'t us

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site