KnowledgeBoat Logo
|

Computer Applications

Write a menu driven program using a method Number() to perform the following tasks:

  1. Accept a number from the user and display it in its Binary Equivalents.
    For example:
    Sample Input: (21)10
    Sample Output: (10101)2
  2. Accept a binary number from the user and display it in its Decimal Equivalents.
    For example:
    Sample Input: (11101)2
    Sample Output: (29)10

Java

User Defined Methods

34 Likes

Answer

import java.util.Scanner;

public class KboatBinary
{
    long decimal2Binary(int n) {
        String str = "";
        int t = n;
        while (t > 0) {
            int d = t % 2;
            str = d + str;
            t /= 2;
        }
        
        long b = Long.parseLong(str);
        return b;
    }
    
    long binary2Decimal(long n) {
        long decimal = 0;
        int base = 1;
        long t = n;
        while (t > 0) {
            int d = (int)(t % 10);
            decimal += d * base;
            base *= 2;
            t /= 10;
        }
        
        return decimal;
    }
    
    void number() {
        Scanner in = new Scanner(System.in);
        System.out.println("Enter 1 to display number in Binary Equivalent");
        System.out.println("Enter 2 to display number in Decimal Equivalent");
        System.out.print("Enter your choice: ");
        int c = in.nextInt();
        
        switch (c) {
            case 1:
            System.out.print("Enter a decimal number: ");
            int num = in.nextInt();
            long binNum = decimal2Binary(num);
            System.out.println("Binary Equivalent");
            System.out.println(binNum);
            break;
            
            case 2:
            System.out.print("Enter a binary number: ");
            long ipNum = in.nextLong();
            long decNum = binary2Decimal(ipNum);
            System.out.println("Decimal Equivalent");
            System.out.println(decNum);
            break;
            
            default:
            System.out.println("Incorrect Choice");
            break;
        }
    }
}

Variable Description Table

Program Explanation

Output

BlueJ output of Write a menu driven program using a method Number() to perform the following tasks: (a) Accept a number from the user and display it in its Binary Equivalents. For example: Sample Input: (21) 10 Sample Output: (10101) 2 (b) Accept a binary number from the user and display it in its Decimal Equivalents. For example: Sample Input: (11101) 2 Sample Output: (29) 10BlueJ output of Write a menu driven program using a method Number() to perform the following tasks: (a) Accept a number from the user and display it in its Binary Equivalents. For example: Sample Input: (21) 10 Sample Output: (10101) 2 (b) Accept a binary number from the user and display it in its Decimal Equivalents. For example: Sample Input: (11101) 2 Sample Output: (29) 10

Answered By

7 Likes


Related Questions