二进制转换开始时输出不显示零

Output not displaying zeros in the beginning of binary conversions

我试着搜索这个特定问题的答案,我可以看到格式选项以及如何在左侧填充零,但我的输出不能有十进制 space 指定的零,只能是转换结果中的零。例如,如果我将 45 转换为二进制,它应该显示 00101101 但它显然会省略前两个零,并显示 101101。如果我格式化输出,它会根据格式规范显示额外或更少的零。我是初学者,不太擅长JAVA。感谢所有帮助。这是针对我的问题的部分代码:

public class DecimalToBinary {
public String toBinary(int b) {
    if (b==0) {
        return "0";
        }
        String binary = "";
        while (b > 0 && b < 256) {
            int rem = b % 2;
            binary = rem + binary;
            b = b / 2;
        }
    return binary;
}

//主线:

public static void main(String[] args) {
    int Choice;
    Scanner input = new Scanner(System.in);
    DecimalToBinary convertD2B = new DecimalToBinary();
    BinaryToDecimal convertB2D = new BinaryToDecimal();
    do{
    System.out.println("Hello! What would you like to do today? Please enter 1, 2, or 3 based on the following: "+"\n"+
    "1. Convert Decimal to Binary"+"\n"+"2. Convert Binary to Decimal"+"\n"+"3. Exit");
    Choice = input.nextInt();
    if(Choice==1){
        System.out.println("Enter a Decimal Number between 0 to 255: ");
        int decimalNumber = input.nextInt();
        if(decimalNumber<256)
            {String output = convertD2B.toBinary(decimalNumber);
            System.out.println("The Binary equivalent of "+decimalNumber+" is: "+output);
            }
        else
            {System.out.println("Please start over and enter a number between 0 and 255.");}
    }

如果 output 是一个字符串,那么您可以在打印前在它前面加上一些零。

只需测量 output 的长度并在其前面添加 "0" 字符串,8 - length 次。

您可以使用printf 进行格式化输出。例如,此行生成由 5 位数字组成的参数值 2 的输出。如果需要,它将用前导 0 填充。

System.out.printf("%05d", 2);  // output is 00002

但这只适用于小数而不适用于字符串。但是,如果您手动计算差异并输入 0 作为参数,则可以使用它。

System.out.printf("The Binary equivalent of "+decimalNumber+" is: %0" + (8 - output.length()) + "d%s\n", 0, output);