Проблема с Java десятичного в двоичный преобразователь - PullRequest
0 голосов
/ 15 марта 2020

Я изучаю 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
}

}

1 Ответ

0 голосов
/ 15 марта 2020

Как-то так должно работать.

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