我正在尝试在特定元素位置用字符填充用户创建的数组(在3-11号奇数之间)以获取图案。用户输入的内容既作为行数又作为列数,因此,如果像下面的示例中那样输入5,则将得到5 x 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;
}
答案 0 :(得分: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;
我很确定我仍然对复杂的事情感到满意,但是我对这段代码感到满意