简体   繁体   English

如何在Java中的2d锯齿状数组周围打印边框

[英]How to print a border around a 2d jagged array in Java

I need to place a border around a 2d jagged array like this one: 我需要在像这样的二维锯齿状阵列周围放置边框:

{' ', ' ', ' '}
{' ', ' ', ' '}
{' ', ' ', ' ', ' '}
{' ', ' ', ' ', ' '}
{' ', ' ', ' ', ' ', ' '}

To print something that looks like this: 要打印如下内容:

*****
*   *
*   *
*    *
*    *
*     *
*******

I think I have a start with the top row: 我想我从第一行开始:

for (int i = 0; i < a.length; i++) {
          System.out.print('*');          
    }

but I am stumped beyond that (if it's even correct). 但我为此感到困惑(如果是正确的话)。 How could I print in between the dimensions of the arrays? 如何在数组尺寸之间进行打印?

Thanks 谢谢

We can handle this by printing the top border, then printing the middle content, and finally printing the bottom border. 我们可以通过打印顶部边框,然后打印中间内容,最后打印底部边框来处理此问题。 The trick here is that we don't actually have to worry about going outside the indices of the array. 这里的技巧是,我们实际上不必担心超出数组的索引范围。 For the middle portion of the pattern, we just iterate the bounds of the array, and append a border on both sides. 对于模式的中间部分,我们仅迭代数组的边界,并在两侧添加边框。 The top and bottom borders don't actually involve the array contents, except for the size of the first and last jagged 1D array. 除了第一个和最后一个锯齿状一维数组的大小以外,顶部和底部边框实际上并不涉及数组内容。

for (int i=0; i <= array[0].length + 1; ++i) {
    System.out.print("*");
}
System.out.println();

for (int r=0; r < array.length; ++r) {
    System.out.print("*");
    for (int c=0; c < array[r].length; ++c) {
        System.out.print(array[r][c]);
    }
    System.out.println("*");
}

for (int i=0; i <= array[array.length-1].length + 1; ++i) {
    System.out.print("*");
}

*****
*   *
*   *
*    *
*    *
*     *
*******

I would start with a method to build a single line. 我将从建立一条直线的方法开始。 That could be done with a StringBuilder . 可以使用StringBuilder完成。 Start with a * , add all of the characters passed in as input and another * at the end. *开头,添加作为输入传入的所有字符,并在末尾添加另一个* Return that as a String . String返回。 Like, 喜欢,

public static String oneLine(char[] ch) {
    StringBuilder sb = new StringBuilder();
    sb.append("*");
    sb.append(Stream.of(ch).map(String::valueOf).collect(Collectors.joining("")));
    sb.append("*");
    return sb.toString();
}

Then we can call that to build all of the lines. 然后我们可以调用它来构建所有行。 The outline can be built by replicating the first and last entries (with all spaces as stars). 可以通过复制第一个和最后一个条目(所有空格均为星号)来构建轮廓。 Like, 喜欢,

char[][] arr = { { ' ', ' ', ' ' }, { ' ', ' ', ' ' }, { ' ', ' ', ' ', ' ' }, 
        { ' ', ' ', ' ', ' ' }, { ' ', ' ', ' ', ' ', ' ' } };
System.out.println(oneLine(arr[0]).replace(' ', '*'));
for (char[] ch : arr) {
    System.out.println(oneLine(ch));
}
System.out.println(oneLine(arr[arr.length - 1]).replace(' ', '*'));

Outputs (as requested) 输出(根据要求)

*****
*   *
*   *
*    *
*    *
*     *
*******

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM