0% found this document useful (0 votes)
8 views2 pages

Decimal to binary conversion

The document provides a Java program that allows users to convert between decimal and binary integers through a menu-driven interface. Users can choose to convert a decimal integer to its binary equivalent or a binary integer to its decimal equivalent. The program includes methods for each conversion and handles user input and output accordingly.

Uploaded by

hkschool999
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views2 pages

Decimal to binary conversion

The document provides a Java program that allows users to convert between decimal and binary integers through a menu-driven interface. Users can choose to convert a decimal integer to its binary equivalent or a binary integer to its decimal equivalent. The program includes methods for each conversion and handles user input and output accordingly.

Uploaded by

hkschool999
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

1.

Write a menu-driven prog to perform the following as per user's choice :


Choice 1 or A or a :
Accept a Decimal Integer and output its Binary equivalent .

Choice 2 or B or b :
Accept a Binary Integer and output its Decimal equivalent .

Design main()- Accepts user's choice , invokes the Methods and displays
desired Output.

Sol.

import java.util.*;
public class Main {
public static String decimalToBinary(int decimal)
{
String binary = "";
while (decimal > 0)
{
binary = (decimal % 2) + binary;
decimal /= 2;
}
return binary;
}
public static int binaryToDecimal(int binary)
{
int decimal = 0;
int power = 0;
while (binary > 0)
{
decimal += (binary % 10) * Math.pow(2, power);
binary /= 10;
power++;
}
return decimal;
}
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.println("Menu:");
System.out.println("1. Convert decimal to binary");
System.out.println("2. Convert binary to decimal");
System.out.println("3. Exit");
System.out.print("Enter your choice: ");
char choice = in.next().charAt(0);
switch (choice)
{
case '1':
case 'A':
case 'a':
System.out.print("Enter a decimal integer: ");
int decimal = in.nextInt();
System.out.println("The binary equivalent is: " + decimalToBinary(decimal));
break;
case '2':
case 'b':
case 'B':
System.out.print("Enter a binary integer: ");
int binary = in.nextInt();
System.out.println("The decimal equivalent is: " + binaryToDecimal(binary));
break;
default:
System.out.println("Invalid choice.");
}
}
}

You might also like