由于某种原因,我试图转换为8位的位中出现“空”,但我不知道为什么。我认为这是因为我没有将numArray设置为任何东西吗?

/*
OUTPUT
null00000011
10110100
null00101011
null00000010
10110101
null00101010
*/


如果我做错了什么,请在下面告诉我。

public class cache
{
    static int [] ref = {3,180,43,2,181,42};
    static String numArr [] = new String[6];
    static String numArray [] = new String[6];
    static Scanner in = new Scanner(System.in);

    public static void main(String [] args)
    {
        //System.out.println(intToBinary(3,8));
        addZero(intToBinary());
        display();

    }

    public static String[] intToBinary()
    {

        for(int i =0 ;i<ref.length;i++)
        {
            //int num = in.nextInt();
            numArr[i]= Integer.toBinaryString(ref[i]);

        }
        return numArr;
    }
    public static void display()
    {
        for(int i=0; i< numArray.length;i++)
        {
            System.out.println(numArray[i]);
        }
    }
    public static void addZero(String[] me)
    {

        for(int i=0;i<me.length;i++)
        {
            int num = 8 - me[i].length();
            if(me[i].length()==8)
            {
                numArray[i]=me[i];
            }else
            {
                for(int j=0;j<num;j++)
                {
                    numArray[i]+="0";
                }
                numArray[i]+=me[i];
            }
        }
    }
}

最佳答案

问题是null"0"等于null0

numArray[i]+="0";


您可以将其更改为

if (numArray[i].length() == 0)
  numArray[i]="0";
else
  numArray[i]+="0";

10-08 12:56