简体   繁体   English

创建一个java程序将十进制转换为二进制?

[英]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. 在尝试将answers2中的数字转换为二进制或十进制时,我无法弄清楚如何实际拆分answer2以使其工作。 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. 我是Java的新手,仍在努力学习绳索。

  2. In converting decimal to binary, its printing out 6-bit or another bit, I want it specifically to be 8-bit. 在将十进制转换为二进制时,它打印出6位或另一位,我希望它特别是8位。 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 我没有改变你的转换逻辑,而是改变决策过程并用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. 另外:为什么使用static for binaryToDecimal方法而不是二进制。 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. 1)在尝试将answers2中的数字转换为二进制或十进制时,我无法弄清楚如何实际拆分answer2以使其工作。 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. 我是Java的新手,仍在努力学习绳索。

What do you mean "how to actually split the answer2"? 你是什​​么意思“如何实际分开答案2”?

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. 2)在将十进制转换为二进制时,它打印出6位,我希望它特别是8位。 How can I fix this? 我怎样才能解决这个问题?

If you want 8 bit you can add enough padding 0s at the beginning of the binary string: 如果你想要8位,你可以在二进制字符串的开头添加足够的填充0:

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);
    }
}

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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