Ricki - 4 years ago 99

Java Question

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.

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

@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:

```
**********
* *
* *
* *
* *
* *
* *
* *
* *
**********
```

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**