第二个数组不打印

时间:2014-12-20 06:50:42

标签: java arrays binary

当我在编译器中运行代码时,第二个数组由于某种原因不打印,即使它与创建第一个数组副本和粘贴的代码基本相同。第一个数组打印。

有人能告诉我为什么第二个阵列没有打印?

 public static void main(String[] args)
 {
   Scanner s = new Scanner(System.in);
    int n;
    int i = 0;
    int count = 0;

    int x;
    int d = 0;
    int count2 = 0;

    System.out.println("Enter a base ten number between 0 and 255, inclusive.");
    n = s.nextInt();
    System.out.println("Enter a base ten number between 0 and 255, inclusive.");
    x = s.nextInt();
    int[] bin = new int[8];
     int[] bin2 = new int[8];
    while (count < 8) {
        bin[i] = n % 2;
        i++;
        n = n / 2;
        count++;
    }

   System.out.print("First binary number: ");
    for (int j = i - 1; j >= 0; j--) {


      System.out.print(bin[j] + " ");
    }


    while (count2 < 8) {
        bin2[d] = x % 2;
        d++;
        x = x / 2;
        count2++;
    }

   System.out.print("\n\nSecond binary number: ");
    for (int z = x - 1; z >= 0; z--) {


      System.out.print(bin2[z] + " ");
    }

}

3 个答案:

答案 0 :(得分:1)

更改循环
for (int z = x - 1; z >= 0; z--) {

for (int z = d - 1; z >= 0; z--) {

与前面的循环一样,x可能已经变为0,而你正试图这样做:

z = -1 and z >=0
在你的for循环中

,这就是为什么它不进入for循环。

答案 1 :(得分:1)

在第一个循环中,您从i倒数到零。在第二个循环中,等效id

但是,不是从d开始倒计时,而是从x倒数,这会给你不正确的结果。所以改变:

for (int z = d - 1; z >= 0; z--) {
  System.out.print(bin2[z] + " ");
}

答案 2 :(得分:0)

更改此

System.out.print("\n\nSecond binary number: ");
for (int z = x - 1; z >= 0; z--) {


  System.out.print(bin2[z] + " ");
}

System.out.print("\n\nSecond binary number: ");
for (int z = d - 1; z >= 0; z--) {


  System.out.print(bin2[z] + " ");
}