当前位置: 首页 > 知识库问答 >
问题:

如何从两个不同的数组中交替打印元素?

严峰
2023-03-14

我有两个2D数组,都是3x3。

|      |
|      |    Note: 6 spaces " " per row / 3 spaces " " per cell 
|      |
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个答案

孙修德
2023-03-14

我想我理解你了。您错过了一些东西,比如另一个块,我建议您仔细查看我下面的评论,

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.
}

输出是您请求的

|       |   
|       |   
|       |   
 类似资料:
  • 有人能帮忙吗?选择2不起作用。当用户输入员工姓名时,它应该显示员工ID,但当用户输入姓名时,不会打印任何内容。代码没有错误。 //搜索员工数据公共静态无效搜索(string[]emplNames,int[]emplid){

  • 我现在的代码: 我希望它打印两个数组的交集,而不需要再次打印相同的数字。 E、 g:code>[1,2,2,1]和的交点应该只打印一次,而不是像我现在的代码那样。

  • 问题内容: 我正在尝试编写一个小程序,该程序在数组中打印出不同的数字。例如,如果用户输入1,1,3,5,7,4,3,则该程序将仅打印出1,3,5,7,4。 我在else if函数中遇到错误。 到目前为止,这是我的代码: 问题答案: 首先,“ ”语句是不正确的,因为您没有为if提供任何条件(如果需要if,则需要编写“ ”)。 其次,您不能 在内部 循环中决定是否应打印一个值:代码的工作方式是 为每个

  • 问题内容: 写一个方法 公共静态ArrayList merge(ArrayList a,ArrayList b) 合并两个数组列表,两个数组列表中的元素交替出现。如果一个数组列表短于另一个数组列表,则请尽可能长地交替,然后附加较长数组列表中的其余元素。例如,如果a是 1 4 9 16 b是 9 7 4 9 11 然后合并返回数组列表 1 9 4 7 9 4 16 9 11 我尝试做的是编写一个带i

  • 这里有两个数据帧: 预期数据帧: 以及实际数据帧: 现在两个数据帧之间的区别是: 我们使用的是except函数df1.except(df2),但问题是,它返回的是不同的整行。我们希望看到该行中哪些列不同(在本例中,“romin”和“romino”与“emp_name”不同)。我们在这方面遇到了巨大的困难,任何帮助都会很好。

  • 我正在尝试使用CSS或jQuery在两个图像之间不断切换。我的工作还可以,但它基本上是把一个图像放在另一个上面,如果我使用的图像是透明的,这会引起问题。 null null 代码编号:https://codepen.io/rhys_eng/pen/nwdwxao