Ricki
Ricki

Reputation: 151

Make a square shape of asterisc around border of 2D Array

I am trying to fill with asterisks only the outside border of a 2D Array I have half of it done, but it seems that I cant get it to fill the last column and the last row in the 2D array.

so far I can do this

and here is my code:

for (int i = 0; i < array.length; i++) 
{
    for (int j = 0; j < array.length; j++) 
    {
        if (array[i][j] == array[0][j] || array[i][j] == array[i][0])
        {
            array[i][j] = "*";
        }
    }
}

but obviously I want to finish the Square shape around the 2D array, so I tried something like this.

for (int i = 0; i < array.length; i++) 
{
    for (int j = 0; j < array.length; j++) 
    {
        if (array[i][j] == array[array.length - 1][j]
                    || array[i][j] == array[i][array.length - 1]) 
        { 
            array[i][j] = "*";
        }
    }
}

My idea was just to go to the last valid position in the 2D array and simply print the column and the row but it doesn't seem to work. Thanks to all the help I can get, I really appreciate it as I'm a learner in Java.

Upvotes: 0

Views: 6600

Answers (2)

GustavoCinque
GustavoCinque

Reputation: 166

@Ricki, your line of thinking was right, but what you didn't consider is that array[i][j] == array[array.length - 1][j] doesn't compare the "shell" per say, but the inner value of it, so, even if array[1][1] != array[2][1], if their values are null they are equals.

Try using this code:

int _i = 10;
int _j = 10;
String[][] array = new String[_i][_j];
for (int i = 0; i < _i; i++) {
    for (int j = 0; j < _j; j++) {
        if(i==0 || j == 0 || i == _i-1|| j == _j-1){
            array[i][j] = "*";
        }
    }
}

What i've done is comparing the first row (i==0), the first column (j==0), the last row (i == _i-1) and the last column (j == _j-1).

And then:

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

Upvotes: 1

Vishal Gajera
Vishal Gajera

Reputation: 4207

you can do something likewise,

public static void main(String[] args) {
    int n = 5;
    String [][] array = new String[n][n]; // 2-dimension array define...
    for (int i = 0; i < array.length; i++) {
        for (int j = 0; j < array.length; j++) {
            if(i == 0 || (i == array.length-1 || j==0 || j==array.length-1)){ // if top,left,right,bottom line then this...
                array[i][j] = "*|";
            }else{ // if not border line then this...
                     array[i][j] = "_|";

            }
        }

    }

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

OUTPUT : enter image description here

Upvotes: 0

Related Questions