在2D阵列的边框周围制作一个正方形的星号 [英] Make a square shape of asterisc around border of 2D Array

查看:35
本文介绍了在2D阵列的边框周围制作一个正方形的星号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图仅用星号填充2D数组的外部边界,但已完成一半,但似乎无法填充2D数组的最后一列和最后一行.

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.

到目前为止,我可以做到

这是我的代码:

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] = "*";
        }
    }
}

但是显然我想完成2D数组周围的Square形状,所以我尝试了类似的方法.

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] = "*";
        }
    }
}

我的想法是转到2D数组中的最后一个有效位置,然后仅打印列和行,但似乎不起作用.感谢我所能提供的所有帮助,因为我是Java的学习者,对此我感到非常感谢.

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.

推荐答案

@Ricki,您的思路是正确的,但是您没有考虑的是 array [i] [j] == array [array.length-1] [j] 不会比较每个人说的"shell",而是它的内部值,所以即使 array [1] [1]!= array [2] [1] ,如果它们的值是 null ,则它们等于.

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

尝试使用此代码:

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] = "*";
        }
    }
}

我所做的是比较第一行( i == 0 ),第一列( j == 0 ),最后一行( i == _i-1 )和最后一列( j == _j-1 ).

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).

然后:

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

这篇关于在2D阵列的边框周围制作一个正方形的星号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆