简体   繁体   中英

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 . Start with a * , add all of the characters passed in as input and another * at the end. Return that as a 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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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