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

5

我正在开发一个程序,将显示三个选项:

  • 将十进制转换为二进制
  • 将二进制转换为十进制
  • 退出。

如果用户选择“退出”,系统会接受该选项并说“再见”。

目前我的代码如下:

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

我正在遇到的问题是这样的。
  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
    

你能举一个生成6位数字的例子吗? - Scott Hunter
只需根据需要在二进制字符串前面填充“0”即可。 - OldProgrammer
它不总是6。我刚意识到这一点,它正在进行中。 输入你的选择:1 输入一个数字:16 8位二进制表示是:10000 - chatslayer
answer2 是一个整数。因此它已经是二进制的了。你需要从十进制开始,这意味着需要使用字符串。 - user207421
@EJP 当然,这基本上是正确的...但是Java库隐式地将它们读取和打印为十进制,因此任何将int视为其中之一的处理在尝试编写转换程序时都有些误导性。只有当二进制和十进制表示均作为字符串处理时,才能得到忠实的算法(其中不会隐式进行任何转换)。 - Linus
3个回答

1
你可以使用 switch case 来执行一系列操作。switch 根据选择执行一个操作,你也可以设计多个操作。为了更好的理解,请参考link
我没有改变你的转换逻辑,而是用 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

            }
        }
    }
}

输出

==================================
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

此外:为什么在binaryToDecimal方法中使用静态而不是在binary中使用静态。我将两种方法都设置为对象级别。这样做更有意义,因为您正在为选择创建对象。但是,为每个选择创建对象是不必要的,您可以多次使用相同的对象,因为您没有使用任何成员变量来完成工作,请参见下面的代码
        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;

        } 

0
1)在尝试将answers2中的数字转换为二进制或十进制时,我无法弄清楚如何实际拆分answer2以使其起作用。我考虑过使用循环,但不确定还能做什么。你能告诉我需要做什么吗?我是Java新手,仍在努力学习。

你说的“如何实际拆分answer2”是什么意思?

要将二进制字符串转换为十进制,我建议你

int decimal = Integer.parseInt(binaryString, 2)

在另一方面,你可以使用

String binary = Integer.toBinaryString(decimalNumber);

2)在将十进制转换为二进制时,它打印出6位,我希望它特别是8位。我该怎么办? 如果您想要8位,则可以在二进制字符串开头添加足够的填充0:
String binaryString = Integer.toBinaryString(10);
for(int i = 8 - binaryString.length(); i > 0; i--)
    binaryString = "0" + binaryString;

当然这不是最高效的方式,但我认为这样也可以。


0

这是我编写这个程序的方法。它完全基于递归。

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

}


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接