简体   繁体   中英

Creating a java program to convert decimal to binary?

I'm working on a program that will display three choices. The three are:

  • Converting decimal to binary
  • Convert binary to decimal
  • Exit.

If the user writes "Exit" in the choice, the system to take the number and say "Goodbye".

As of right now this is what I have.

import java.util.Scanner;

public class binary {

    public String toBinary(int n) {
        if (n == 0) {
            return "0";
        }
        String binary = "";
        while (n > 0) {
            int rem = n % 2;
            binary = rem + binary;
            n = n / 2;
        }
        return binary;
    }

    public static int binaryTodecimal(int i) {
        int n = 0;
        for (int pow = 1; i > 0; pow *= 2, i /= 10)
            n += pow * (i % 10);
        return n;
    }

    public static void main(String[] args) {

        int answer2 = 0;
        String answer;

        final int info = 10;
        for (int i = 0; i < info; i++) {

            Scanner kb = new Scanner(System.in);
            System.out.println("==================================");
            System.out.print("Enter your choice: ");
            answer = kb.next();

            if (answer.equalsIgnoreCase("3"))
                System.exit(0);

            System.out.print("Enter a number: ");
            answer2 = kb.nextInt();

            binary decimalToBinary = new binary();
            String binary = decimalToBinary.toBinary(answer2);

            if (answer.equals("1"))
                System.out.println("The 8-bit binary representation is: " + binary);

            binary bd = new binary();
            int n = bd.binaryTodecimal(answer2);

            if (answer.equals("2"))
                System.out.println("The decimal representation is: " + answer2);

The questions I'm having is this.

  1. In trying to convert the number in answers2 to binary or decimal, I cannot figure out how to actually split the answer2 up for this to work. I thought of doing a loop, but not sure what else I can do. Could you by chance tell me what I need to do? I'm new in Java, still trying to learn the ropes.

  2. In converting decimal to binary, its printing out 6-bit or another bit, I want it specifically to be 8-bit. How can I fix this? Example:

     Enter your choice: 1 Enter a number: 16 The 8-bit binary representation is: 10000 

You can use a switch case for list of actions to be done. A switch does an action based on the choice, you may as well design to do multiple actions. for better understanding follow this link

I have not changed an of your conversion logic but the decision process and replaced it with switch

import java.util.Scanner;

public class BinaryToDecimal {

    public String toBinary(int n) {
        if (n == 0) {
            return "0";
        }
        String binary = "";
        while (n > 0) {
            int rem = n % 2;
            binary = rem + binary;
            n = n / 2;
        }
        return binary;
    }

    public int binaryTodecimal(int i) {
        int n = 0;
        for (int pow = 1; i > 0; pow *= 2, i /= 10)
            n += pow * (i % 10);
        return n;
    }

    public static void main(String[] args) {

        int answer2 = 0;
        String answer;

        final int info = 10;
        for (int i = 0; i < info; i++) {

            Scanner kb = new Scanner(System.in);
            System.out.println("==================================");
            System.out.print("Enter your choice: ");
            answer = kb.next();

            switch (answer) {
            case "1": // if the answer is one do this action
                System.out.print("Enter a number: ");
                answer2 = kb.nextInt();
                BinaryToDecimal decimalToBinary = new BinaryToDecimal();
                String binary = decimalToBinary.toBinary(answer2);
                System.out.println("The 8-bit binary representation is: " + binary);
                break; // leave the switch 

            case "2": // if answer is 2 do the following actions
                System.out.print("Enter a number: ");
                answer2 = kb.nextInt();
                BinaryToDecimal bd = new BinaryToDecimal();
                int n = bd.binaryTodecimal(answer2);
                System.out.println("The decimal representation is: " + n);
                break; // leave the switch case

            case "3": // when the answer is 3
                System.out.println("Goodbye");
                System.exit(0);
                // break; you need not use here because you have an exit call

            }
        }
    }
}

output

==================================
Enter your choice: 1
Enter a number: 25
The 8-bit binary representation is: 11001
==================================
Enter your choice: 2
Enter a number: 11001
The decimal representation is: 25
==================================
Enter your choice: 2
Enter a number: 1000000
The decimal representation is: 64
==================================
Enter your choice: 3
Goodbye

in addition : why use static for binaryToDecimal method but not for binary. I have made both the method object level. it makes more since since you are creating an object for a choice. But creating an object for every choice is not need you can use the same object created multiple time since you have not using any member variables to get your job done, see the below code

        BinaryToDecimal decimalToBinary = new BinaryToDecimal();
        Scanner kb = new Scanner(System.in);
        System.out.println("==================================");
        System.out.print("Enter your choice: ");
        answer = kb.next();

        switch (answer) {
        case "1":
            System.out.print("Enter a number: ");
            answer2 = kb.nextInt();
            String binary = decimalToBinary.toBinary(answer2);
            System.out.println("The 8-bit binary representation is: " + binary);
            break;

        case "2":
            System.out.print("Enter a number: ");
            answer2 = kb.nextInt();
            int n = decimalToBinary.binaryTodecimal(answer2);
            System.out.println("The decimal representation is: " + n);
            break;

        case "3":
            System.out.println("Goodbye");
            System.exit(0);
            break;

        } 

1) In trying to convert the number in answers2 to binary or decimal, I cannot figure out how to actually split the answer2 up for this to work. I thought of doing a loop, but not sure what else I can do. Could you by chance tell me what I need to do? I'm new in Java, still trying to learn the ropes.

What do you mean "how to actually split the answer2"?

to convert from binary string to decimal i suggest you

int decimal = Integer.parseInt(binaryString, 2)

on the other side you can use

String binary = Integer.toBinaryString(decimalNumber);

2) In converting decimal to binary, its printing out 6-bit, I want it specifically to be 8-bit. How can I fix this?

If you want 8 bit you can add enough padding 0s at the beginning of the binary string:

String binaryString = Integer.toBinaryString(10);
for(int i = 8 - binaryString.length(); i > 0; i--)
    binaryString = "0" + binaryString;

Of course this is not the most efficient way, but i think it's fine

Here's how i did this program.It's completely based on recursion

import java.util.*;

class Dec_To_Bin{
        public static void main(String args[]){
        Scanner in=new Scanner(System.in);
        System.out.print("Enter the decimal number:>");
        int n=in.nextInt();
        Dec_To_Bin ob=new Dec_To_Bin();
        ob.binconv(n,0);
    }
public void binconv(int n,int c){
    if(c>7){
        return ;
    }
    else{
        binconv(n/2,c+1);
        System.out.print(n%2);
    }
}

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM