Java 打印';n';长度为'的二进制数;n';使用for循环

Java 打印';n';长度为'的二进制数;n';使用for循环,java,string,loops,for-loop,Java,String,Loops,For Loop,我试着写一个代码,输入一个数字“n”,它会显示长度为“n”的二进制数“n”。数字的顺序无关紧要 e、 g。 我输入3(n=3) 000 001 010 011 100 101 110 111 这就是我目前得到的 String b1="1",b2="0"; String combination="0"; String output="0" for (int k=1; k<=n; k++) { for (int z=1; z<=

我试着写一个代码,输入一个数字“n”,它会显示长度为“n”的二进制数“n”。数字的顺序无关紧要

e、 g。 我输入3(n=3)

000 001 010 011 100 101 110 111 这就是我目前得到的

    String b1="1",b2="0";
    String combination="0";
    String output="0"

    for (int k=1; k<=n; k++) {

            for (int z=1; z<=n; z++)
            {
                combination= b1+b2;
            }
        output = output+combination;





    }
    System.out.println(output);
字符串b1=“1”,b2=“0”;
字符串组合=“0”;
字符串输出=“0”

对于(int k=1;k已经有工具可以在
Integer()
类中打印数字的二进制表示形式

因此,对于
n=3
您需要输出3组二进制数字,每个输出中有3位。
toBinaryString()
接受
int
参数并返回“二进制参数(基数2)表示的无符号整数值的字符串表示形式”。您需要进行一些调整,以在长度仅为2位的二进制表示前面获得适当的填充,即0、1、2、3,分别为00、01、10、11

编辑:当我把我的代码片段复制到一个实际的Eclipse项目中时,我注意到我的填充逻辑不正确。我已经修复了它。这段代码几乎正是你想要的。但我认为你必须做一些精细处理,以获得你想要的输出位数

int n = 4;
int numBits;
String paddingZero = "0";
String binary;

for(int i = 0; i <= n; i++)
{
    numBits = n / 2;
    if(numBits < 2)
    {
        numBits = 2; // Binary should never display less than 2 bits of digits for clarity.
    }

    binary = Integer.toBinaryString(i);
    if(binary.length() < numBits)
    {
        do  
        {
            binary = paddingZero + binary;
        }
        while(binary.length() < numBits);
    }

    System.out.print(binary + " "); // Appends the String representation of the binary digit to the paddingZeroes
}

一旦n>8,numBits逻辑将需要改变一些。这将让您开始。

您有点偏离正轨。下面的链接有几个不同的工作示例,我相信您正在努力实现:


由于n位数字的最大值为
2^n-1
,您可以从零循环到该值,并以二进制格式显示

public static void main (String[] args)
{
    int n = 4;
    String printFormat = "%"+n+"s";
    int max = (int) Math.pow(2, n);
    for (int i=0; i < max; i++) {
      String s = String.format(printFormat, Integer.toString(i, 2)).replace(' ', '0');  
      System.out.println(s);
    }
}
publicstaticvoidmain(字符串[]args)
{
int n=4;
字符串printFormat=“%”+n+“s”;
int max=(int)Math.pow(2,n);
对于(int i=0;i

所以您想添加换行符
\r\n
?您的方法看起来完全错误。您只是多次将“1”和“0”组合在一起。有2^n个值,其中有n个位(在您的示例中为2^3==8)。即使在正确的示例输出中,您也没有输出n个长度为n的数字。您正在输出全部(2^n)长度为n的二进制数。您能接受任何适用的答案吗?
public static void main (String[] args)
{
    int n = 4;
    String printFormat = "%"+n+"s";
    int max = (int) Math.pow(2, n);
    for (int i=0; i < max; i++) {
      String s = String.format(printFormat, Integer.toString(i, 2)).replace(' ', '0');  
      System.out.println(s);
    }
}