javaarrayscoordinatesdimensional

Print hollow rectangle with a 2 dimensional array


I have this code that prints a rectangle using a 2 dimensional array. As you can see I hand-coded the whole array instead of using a loop. What I am looking for is:

  1. How to use a loop to print exactly the same rectangle (with the stars, minuses...)
  2. After this template is created, if I want to place, let's say a char '?' inside the rectangle, I can, for example, call the coordinates tab[5][4], and this will print it.

The problem is a whole column of '?' is printed outside the template. How can I fix this?

NOTE: I don't want to use any of java's Swing or AWT Libraries.

public class HelloWorld{

 public static void main(String []args){
char [][] tab= {
    {'*', '-', '-', '-', '-','*'},
    {'+', ' ',  ' ',  ' ', ' ',  '+'},
    {'+', ' ',  ' ',  ' ', ' ',  '+'},
    {'+', ' ',  ' ',  ' ', ' ',  '+'},
    {'+', ' ',  ' ',  ' ', ' ',  '+'},
    {'+', ' ',  ' ',  ' ', ' ',  '+'},
    {'+', ' ',  ' ',  ' ', ' ',  '+'},
    {'*', '-', '-', '-', '-','*'}


};
int row=8;
int col=6;
for (int i=0; i< row; i++){
    for(int j=0; j< col; j++){
        System.out.print(tab[i][j]+" ");

    }
    System.out.print(tab[5][4]='?');
    System.out.println("");

}

This is my output:

* - - - - - * ?
+           + ?
+           + ?
+           + ?
+           + ?
+        ?  + ?
+           + ?
* - - - - - * ?

Thanks for your help


Solution

  • You can do it like this - Declare an array with the right size and fill it with ' ':

    final int row=8;
    final int col=6;
    char[][] tab = new char[row][col];
    for (int i=0; i< row; i++){
        for(int j=0; j< col; j++){
            tab[i][j] = ' ';
        }
    }
    

    Place the stars at the corners:

    tab[0][0] = '*';
    tab[0][col-1] = '*';
    tab[row-1][0] = '*';
    tab[row-1][col-1] = '*';
    

    For the first and last row:

    for (int i=1; i<col-1; i++) {
        tab[0][i] = '-';
        tab[row-1][i] = '-';
    }
    

    And for all the other rows:

    for (int i=1; i < row-1; i++) {
        tab[i][0] = '+';
        tab[i][col-1] = '+';
    }
    

    Now you can place the '?' wherever you want and print the array.