Java 将零与字符串串联

Java 将零与字符串串联,java,string,Java,String,我试图将零附加到字符串中,使其成为32位数字。但输出不显示附加的零。为什么会这样 System.out.print("\nEnter the linear Address (32bit) :\t"); String linear_hex= sc.nextLine(); String linear_bin= Integer.toBinaryString(Integer.parseInt(linear_hex,16)); if(linear_bin.length()

我试图将零附加到字符串中,使其成为32位数字。但输出不显示附加的零。为什么会这样

    System.out.print("\nEnter the linear Address (32bit) :\t");
    String linear_hex= sc.nextLine();
    String linear_bin= Integer.toBinaryString(Integer.parseInt(linear_hex,16));

    if(linear_bin.length() != 32)
    {

        for(int i= linear_bin.length(); i<=32; i++)
            linear_bin= 0+linear_bin;
    }

我还尝试了
linear\u bin=“0”+linear\u bin
“0”。混凝土(线性)但输出仍然相同。

您的代码对我来说很好:

System.out.print("\nEnter the linear Address (32bit) :\t");
    Scanner sc = new Scanner(System.in);
    String linear_hex= sc.nextLine();
    String linear_bin= Integer.toBinaryString(Integer.parseInt(linear_hex,16));

    if(linear_bin.length() != 32) {         
        // Should be i < 32 instead of i <= 32, else you end up with an extra 0
        // Also consider using StringBuilder instead of String concatenation here
        for(int i= linear_bin.length(); i < 32; i++)
            linear_bin= 0+linear_bin;
    }
    System.out.println(linear_bin);
输出:

Enter the linear Address (32bit) :  12345678
Linear Address = 10010001101000101011001111000
00000000000100100011010001010110
但是,使用
String.format()
方法可以更容易地实现这一点。删除
if
块,并添加此打印语句:

System.out.println(String.format("%32s", linear_bin).replace(' ', '0'));

你的代码对我来说很好:

System.out.print("\nEnter the linear Address (32bit) :\t");
    Scanner sc = new Scanner(System.in);
    String linear_hex= sc.nextLine();
    String linear_bin= Integer.toBinaryString(Integer.parseInt(linear_hex,16));

    if(linear_bin.length() != 32) {         
        // Should be i < 32 instead of i <= 32, else you end up with an extra 0
        // Also consider using StringBuilder instead of String concatenation here
        for(int i= linear_bin.length(); i < 32; i++)
            linear_bin= 0+linear_bin;
    }
    System.out.println(linear_bin);
输出:

Enter the linear Address (32bit) :  12345678
Linear Address = 10010001101000101011001111000
00000000000100100011010001010110
但是,使用
String.format()
方法可以更容易地实现这一点。删除
if
块,并添加此打印语句:

System.out.println(String.format("%32s", linear_bin).replace(' ', '0'));