似乎无法弄清楚如何忽略循环中左右大多数数组元素

问题描述 投票:-2回答:1

我正在尝试将用户制作的数组(大小在3-11之间)填充到某个元素位置的字符以获取模式。用户输入的内容同时充当行数和列数,因此,如果他们在下面的示例中输入5,则他们将获得5乘5的数组。我想要获得这种模式

-----------
 * * * * *
   * * * 
     *  


-----------  

-----------
 * * * * *
 * * * * *
 * * * * *


-----------

这是代码

public static void main (String [] args) {

    int dimension = findDimension();
    char [] [] array2d = new char [dimension] [dimension];

    char star = '*';

    array2d = pointDown(star,dimension);
    System.out.println();
    print(array2d);
}

public static void print(char [] [] arrayParam) {
    for (int hyphen = 0; hyphen < (arrayParam.length*2)+1; hyphen++) {
        System.out.print("-");
    }

    System.out.println();
    for(char[] row : arrayParam)
    {
        for(char c : row)
            System.out.print(" " + c);
        System.out.printf("\n");
    }

    for (int hyphen = 0; hyphen < (arrayParam.length*2)+1; hyphen++) {
        System.out.print("-");
    }
}

问题应该在于这个方法,我认为这个循环之后

public static char [] [] pointDown (char starParam, int dimenParam) {
    char [] [] pointDown = new char [dimenParam] [dimenParam];

    for (int i = 0; i < dimenParam; i++){
        for (int j = 0; j < dimenParam; j++) {
            pointDown[i][j] = ' ';
// I fill the positions first with blank spaces then add the characters
// with the loop below
        }
    }

/* Problem should be in this loop, Is there even a pattern to it though
 * since columns would have to account for both the last and beginning
 * columns after the first loop? Should I make variables for those or is
 */ there a simpler way to do it that I'm missing? 

    for (int i = 0; i <= dimenParam/2; i++) {
        for (int j = 0; j < dimenParam; j++) {
            pointDown[i][j] = starParam;
        }
    }

    return pointDown;
}
java arrays for-loop format output
1个回答
0
投票

更新:在考虑到我被告知的内容后,我能够找出问题所在。这是代码应该是什么样子

char [] [] pointDown = new char [dimenParam] [dimenParam];

    for (int i = 0; i < dimenParam; i++){
        for (int j = 0; j < dimenParam; j++) {
            pointDown[i][j] = ' ';
// As before this part fills the array with blank spaces
        }
    }

    int columnEnd = dimenParam; // Set up a variable to hold how far the column goes to
    int j = 0;   
    for (int row = 0; row <= dimenParam/2; row++) {
        for (int column = j; column < columnEnd; column++) {
            pointDown[row][column] = starParam;
        }
        columnEnd--;  // I had to decrease the ending column in the outer loop
        j++;          // Originally I had this in the inner loop for the longest time
                      // By moving it to the outer loop I avoid out of Bounds and runtime errors

    }
    return pointDown;

我很确定我仍然会处理复杂的事情,但我很满意这段代码

© www.soinside.com 2019 - 2024. All rights reserved.