如何在两个不同阵列的打印元素之间切换?

时间:2014-07-10 00:14:15

标签: java arrays printing

我有两个二维数组,都是3x3。

我想打印出这样的边框和空格,如下所示:

|      |
|      |    Note: 6 spaces " " per row / 3 spaces " " per cell 
|      |

我这样做的思考过程就是将2D数组视为坐标系,并将外边缘指定为1以指示打印边框“|”对于border [] []。然后我会为每个单元格为空间[] []分配3个空格。然后我会逐行和替换打印语句为border [] []和space [] []。

所以,它会一行一行地进行。

print left border -> print spaces -> don't print border -> print spaces -> print right border -> print spaces

或者澄清一下我想做的事情:

border[0][0] = 1 --> print left border "|"
space[0][0] = 1 --> print space "   "
border[0][1] = 0 --> DO NOT print border "|"
space[0][1] = 1 --> print space "   "
border[0][2] = 1 --> print border "|"
space[0][2] = 1 --> print space "   "

所以第一行是:

 |      |

以及每一行等等。


所以我的问题是:

如何在两个不同阵列的打印元素之间切换?


我试过

    int border[][] = new int[3][3];
    int space[][] = new int[3][3];

    for(int i=0;i<border.length; i++){
        for(int j=0; j<space.length;j++){
            //Assigning Left and Right borders
            border[0][j] = 1;
            border[border.length-1][j] = 1;
            //Assigning spaces for every cell
            space[i][j] = 1;

            //Printing????
            if(border[i][j] == 1){
                System.out.print("|");
            }

            if(space[i][j] == 1){
                System.out.print("   ");
            }

        }
        System.out.println();
    }

但打印出来

|   |   |   

|   |   |   

1 个答案:

答案 0 :(得分:0)

我想我理解你。你遗漏了一些东西,比如其他块,我建议你仔细阅读下面的评论,

int border[][] = new int[3][3];
int space[][] = new int[3][3];
for (int[] b : border) {  // <-- lets first create border arrays
  b[0] = b[2] = 1;        // <-- combine the 1s.
  b[1] = 0;              
}
for (int[] s : space) {   // <-- now space arrays
  s[0] = s[1] = s[2] = 1; // <-- combine the 1s.
}
// Now border and space are setup
for (int i = 0; i < border.length; i++) { 
  for (int j = 0; j < border[0].length; j++) {
    if(border[i][j] == 1) {
        System.out.print("|");
    } else { // <-- You need an else block
      System.out.print(" ");          
    }
    if(space[i][j] == 1){ // <-- space is pointless. This is always true.
        System.out.print("   ");
    }
  }
  System.out.println(); // <-- new line.
}

输出是您要求的

|       |   
|       |   
|       |