Java十进制到二进制转换器的麻烦

问题描述 投票:0回答:1

[我正在学习Java,并且一直在尝试构建此转换器超过一个星期,但是这种尝试有时会留下必要的0,并且也不会为输入“ 1”给出结果。

此代码已导入javax.swing。*; //允许“ JOptionPane.showInputDialog”,这是对键入信息的请求加上一条消息

public static void main(String[] args) {
    // TODO Auto-generated method stub
        char number;
        int input, length;
        String reversedBinary = "", binary = "";

        input = Integer.parseInt(JOptionPane.showInputDialog
                ("What number would you like converted to binary?")); // Requesting user to give input

        do {   // gets the reversed binary. For instance: 5 = 101
            reversedBinary = reversedBinary + "" + input % 2;
            input = input/2;
        } while (input > 0);

        length = reversedBinary.length();
        length--; // getting the usable position numbers instead of having length give me the position one ahead

        while (length > 0) { // some code to reverse the string
            number = reversedBinary.charAt(length);
            binary = binary + number;
            length--; // "reversedBinary" is reversed and the result is input into "binary"
        }
        System.out.print("The number converted to binary is: " + binary); // output result
}

}

java binary
1个回答
0
投票

这样的事情应该起作用。

    input = Integer.parseInt(JOptionPane.showInputDialog
            ("What number would you like converted to binary?")); // Requesting user to give input
    String BinaryStr="";
    int i = 0;
    while (input > 0){   
        BinaryStr= BinaryStr+  input % 2; 
        input = input/2;
        i++; 
    } 
    for (int j = i - 1; j >= 0; j--) 
        System.out.print(BinaryStr.charAt(j)); 
© www.soinside.com 2019 - 2024. All rights reserved.