Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/373.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/go/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java十进制到二进制转换器的故障_Java_Binary - Fatal编程技术网

Java十进制到二进制转换器的故障

Java十进制到二进制转换器的故障,java,binary,Java,Binary,我正在学习Java,并且已经尝试构建这个转换器一周多了,但是这个尝试有时会遗漏一个必要的0,也不会给出输入“1”的结果 此代码已导入javax.swing.*;/允许“JOptionPane.showInputDialog”,即请求键入的信息和消息 public static void main(String[] args) { // TODO Auto-generated method stub char number; int input, lengt

我正在学习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
}

}像这样的事情应该行得通

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

为什么要反向收集二进制数字?您只需执行binary=“”+(输入%2)+binary;